6

I have two lists and one of them has 5 elements and the other one has 4 elements. They have some same elements but they have different elements too. I want to create a list with their different element. How can i do it?

Note: 5 elements list is my main list.

cagin
  • 5,772
  • 14
  • 74
  • 130
  • possible duplicate of [Linq find differences in two lists](http://stackoverflow.com/questions/2404301/linq-find-differences-in-two-lists) – AakashM Feb 10 '11 at 12:17

2 Answers2

16

What about this?

var list1 = new List<int>( new []{1,2,3,4,5});
var list2 = new List<int>( new []{1,3,4});
var list3 = list1.Except( list2);

In this case, list3 will contain 2 and 5 only.

EDIT

If you want the elements from both sets that are unique, the following code should suffice:

var list1 = new List<int>( new []{1,2,3,4,5});
var list2 = new List<int>( new []{1,3,4,7});
var list3 = list1.Except(list2).Union(list2.Except(list1));

Will output 2,5 and 7.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • This is not a true set difference though — it merely excludes items in sequence 1 that are also in sequence 2. (It won't include items that are in sequence 2 that are not in sequence 1.) – Paul Ruane Feb 10 '11 at 12:18
  • Jason's answer in [the link provided in the question comment](http://stackoverflow.com/questions/2404301/linq-find-differences-in-two-lists) by AakashM provides a way to produce a true, bidirectional set difference. – Paul Ruane Feb 10 '11 at 12:22
1

If you're curious, the opposite of this is called Intersect

string[] collection1 = new string[] { "1", "7", "4" };
string[] collection2 = new string[] { "6", "1", "7" };

var resultSet = collection1.Intersect<string>(collection2);

foreach (string s in resultSet)
{
    Console.WriteLine(s);
}
Mehrad
  • 4,093
  • 4
  • 43
  • 61