I have 2 separate List and I need to compare the two and get everything but the intersection of the two lists. How can I do this (C#)?
+6
A:
You can use Except to get everything but the intersection of the two lists.
var differences = listA.Except(listB).Union(listB.Except(listA));
If you want to get everything but the union:
var allButUnion = new List<MyClass>();
(The union is everything in both lists - everything but the union is the empty set...)
Reed Copsey
2009-11-05 20:02:29
Given that you're using the word "intersection" to describe what it means in English, doesn't it make sense to use it in the code as well? :)
Jon Skeet
2009-11-05 20:04:19
hehehe, true :)
Reed Copsey
2009-11-05 20:04:48
Although, I seem to remember, when I had to do this for something, this was slightly more efficient than doing the total union and removing the intersection...
Reed Copsey
2009-11-05 20:05:45
+3
A:
Do you mean everything that's only in one list or the other? How about:
var allButIntersection = a.Union(b).Except(a.Intersect(b));
That's likely to be somewhat inefficient, but it fairly simply indicates what you mean (assuming I've interpreted you correctly, of course).
Jon Skeet
2009-11-05 20:02:58
A:
Use Except:
List<int> l1 = new List<int>(new[] { 1, 2, 3, 4 });
List<int> l2 = new List<int>(new[] { 2, 4 });
var l3 = l1.Except(l2);
Nestor
2009-11-05 20:03:31
Wouldn't that just return the items in l1 that are not in l2? What if there are items in l2 not in l1?
Michael Todd
2009-11-05 20:08:38
+10
A:
If you mean the set of everything but the intersection (symmetric difference) you can try:
var set = new HashSet<Type>(list1);
set.SymmetricExceptWith(list2);
Mehrdad Afshari
2009-11-05 20:03:47
A:
var theUnion = list1.Concat(list2);
var theIntersection = list1.Intersect(list2);
var theSymmetricDifference = theUnion.Except(theIntersection);
David B
2009-11-05 20:10:14
A:
Something like this?
String[] one = new String[] { "Merry", "Metal", "Median", "Medium", "Malfunction", "Mean", "Measure", "Melt", "Merit", "Metaphysical", "Mental", "Menial", "Mend", "Find" };
String[] two = new String[] { "Merry", "Metal", "Find", "Puncture", "Revise", "Clamp", "Menial" };
List<String> tmp = one.Except(two).ToList();
tmp.AddRange(two.Except(one));
String[] result = tmp.ToArray();
HackedByChinese
2009-11-05 20:11:40