Suppose that we have two List<int>
's
List<int> list1 = new List<int> { 1, 3, 5, 7 , 9, 11, 18 };
List<int> list2 = new List<int> { 2, 3, 5, 7 , 9, 10, 20, 26, 36 };
question how can i produce;
intersect {3, 5, 开发者_StackOverflow社区7, 9 }
list1Decomp { 1, 11, 18 }
list2Decomp { 2, 10, 20, 26, 36 }
thanks in advance.
var intersection = list1.Intersect(list2).ToList();
var list1Decomp = list1.Except(intersection).ToList();
var list2Decomp = list2.Except(intersection).ToList();
var intersect = list1.Intersect(list2);
var list1Decomp = list1.Except(list2);
var list2Decomp = list2.Except(list1);
In short:
intersect = list1.Intersect(list2);
list1Decomp = list1.Except(list2);
list2Decomp = list2.Except(list1);
These algorithms would be most efficient on an ordered collection (HashSet<> e.g.)
Also beware of using these algorithms on collections of custom types; they really need good IEquatable<> support (i.e. implement the interface and provide your own GetHashCode and Equals). Otherwise, the results will be not what you expect
Although you didn't ask, you might have:
symmDifference = list1.Union(list2).Except(list1.Intersect(list2))
or
symmDifference = new HashSet<int>(list1).SymmetricExceptWith(list2)
精彩评论