Skip to main content
 首页 » 编程设计

c#之在 Liststring> 中查找重复项

2024年02月23日16落叶

在一个包含数十万个条目的列表中,如何将每个条目与列表的其余部分进行比较以查找重复项? 例如,List fileNames 包含“00012345.pdf”和“12345.pdf”,被认为是重复的。标记此类重复项的最佳策略是什么?

谢谢

更新:文件的命名仅限于数字。它们用零填充。重复项是缺少填充的地方。因此,“123.pdf”和“000123.pdf”是重复的。

请您参考如下方法:

您可能想要实现自己的子字符串比较器,以根据子字符串是否包含在另一个字符串中来测试相等性。

这不一定是优化的,但它会起作用。如果您使用的是 .NET 4.0,您也可以考虑使用 Parallel Linq。

编辑:答案已更新,以反射(reflect)经过编辑后改进的问题

void Main() 
{ 
    List<string> stringList = new List<string> { "00012345.pdf","12345.pdf","notaduplicate.jpg","3453456363234.jpg"}; 
 
    IEqualityComparer<string> comparer = new NumericFilenameEqualityComparer (); 
 
    var duplicates = stringList.GroupBy (s => s, comparer).Where(grp => grp.Count() > 1); 
 
    // do something with grouped duplicates... 
 
} 
 
// Not safe for null's ! 
// NB do you own parameter / null checks / string-case options etc ! 
public class NumericFilenameEqualityComparer : IEqualityComparer<string> { 
 
   private static Regex digitFilenameRegex = new Regex(@"\d+", RegexOptions.Compiled); 
 
   public bool Equals(string left, string right) { 
 
        Match leftDigitsMatch = digitFilenameRegex.Match(left); 
        Match rightDigitsMatch = digitFilenameRegex.Match(right); 
 
        long leftValue = leftDigitsMatch.Success ? long.Parse(leftDigitsMatch.Value) : long.MaxValue; 
        long rightValue = rightDigitsMatch.Success ? long.Parse(rightDigitsMatch.Value) : long.MaxValue; 
 
        return leftValue == rightValue; 
   } 
 
   public int GetHashCode(string value) { 
        return base.GetHashCode(); 
   } 
 
}