【问题标题】:Generic method to compare 2 strongly typed list比较 2 个强类型列表的通用方法
【发布时间】:2013-07-25 10:07:12
【问题描述】:

我有以下方法比较 2 个列表(相同类型)并返回差异。如何使此方法接受任何类型的列表?

var differences = list1.Where(x => list2.All(x1 => x1.Name != x.Name))
            .Union(list2.Where(x => list1.All(x1 => x1.Name != x.Name)));

【问题讨论】:

标签: c# .net linq generics compare


【解决方案1】:

要获得两个集合之间的差异(具有顺序独立性和多重性独立性),您可以使用:HashSet<T>.SymmetricExceptWith(IEnumerable<T>)

public static IEnumerable<T> GetSymmetricDifference<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer = null)
{
    HashSet<T> result = new HashSet<T>(list1, comparer);
    result.SymmetricExceptWith(list2);
    return result;
}

在你的情况下,使用它:

var difference = GetSymmetricDifference(list1, list2, new MyComparer());

使用自定义比较器:

public class MyComparer : IEqualityComparer<MyType>
{
    public bool Equals(MyType x, MyType y)
    {
        return x.Name.Equals(y.Name);
    }

    public int GetHashCode(MyType obj)
    {
        return obj.Name == null ? 0 : obj.Name.GetHashCode();
    }
}

【讨论】:

    【解决方案2】:

    这个呢:

    var differences = list1.Except(list2).Union(list2.Except(list1));
    

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      相关资源
      最近更新 更多