I have the following method that compares 2 list (of the same type) and returns the differences. How do I make this method accept lists of any type?
var differences = list1.Where(x => list2.All(x1 => x1.Name != x.Name))
.Union(list2.Where(x => list1.All(x1 => x1.Name != x.Name)));
To get the difference between two sets (with order independency and multiplicity independency), you can use: 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;
}
In your case, to use it:
var difference = GetSymmetricDifference(list1, list2, new MyComparer());
With a custom comparer:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.