tags:

views:

214

answers:

6

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
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
hehehe, true :)
Reed Copsey
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
+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
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
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
+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
Excellent - that looks like the best way of doing it to me.
Jon Skeet
Very nice! That's much cleaner than what I had.
Reed Copsey
A: 
var theUnion = list1.Concat(list2);
var theIntersection = list1.Intersect(list2);
var theSymmetricDifference = theUnion.Except(theIntersection);
David B
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