簡體   English   中英

比較2個強類型列表的通用方法

[英]Generic method to compare 2 strongly typed list

我有以下方法比較2列表(相同類型)並返回差異。 如何使此方法接受任何類型的列表?

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

要獲得兩個集合之間的差異(具有順序獨立性和多重性獨立性),您可以使用: 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();
    }
}

那這個呢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM