C#list -Eliminate通过比较特定属性来复制项目

时间:2016-12-06 11:42:45

标签: c# linq list hashset

List<ClassA> newlist;
List<ClassA> oldlist;

ClassA有20种不同的属性, 我想

  • 比较并从新列表中删除完全匹配的项目
  • 但是,比较必须从ClassA中排除少数属性,因为这些值不是相关的
  • 我正在处理的记录集是 huge (30万到40万)。所以它必须高效

Linq ExceptIntersect似乎不支持上述要求,而且似乎也很慢。 有任何建议可以达到这个目的吗?

3 个答案:

答案 0 :(得分:6)

您可以实施自己的自定义比较器

public class MyEqualityComparer: IEqualityComparer<ClassA> {
  public bool Equals(ClassA x, ClassA y) {
    if (Object.ReferenceEquals(x, y))
      return true;  
    else if ((null == x) || (null == y))
      return false;

    // Your custom comparison here (...has to exclude few properties from ClassA)  
    ... 
  }

  public int GetHashCode(ClassA obj) {
    if (null == obj)
      return 0;

    // Your custom hash code based on the included properties 
    ...
  }
}

然后使用HashSet<ClassA>(我们要从oldlist排除newlist):

HashSet<ClassA> toExclude = new HashSet<ClassA>(
   oldlist, 
   new MyEqualityComparer());

newList.RemoveAll(item => toExclude.Conytains(item));

答案 1 :(得分:0)

前段时间,我发现了以下函数,它允许您区分特定属性。

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
        if (seenKeys.Add(keySelector(element)))
            yield return element;
}

我找不到这个作者,所以谢谢你这位未命名的程序员!

我希望这就是你要找的东西。

答案 2 :(得分:0)

如此处所述:.Distinct() clause not working c# MVC您可以使用GroupBy()Distinct()来完成任务。