c# - Generic method to compare 2 strongly typed list -
i have following method compares 2 list (of same type) , returns differences. how make method accept lists of 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 difference between 2 sets (with order independency , multiplicity independency), 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 case, use it:
var difference = getsymmetricdifference(list1, list2, new mycomparer());
with 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(); } }
Comments
Post a Comment