How to compare elements of two lists with linq?

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

Note. The list of 5 items is my main list.

+6
c # linq
source share
2 answers

How 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 only contain 2 and 5.

EDIT

If you want elements from both sets to be unique, the following code should be sufficient:

 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)); 

2.5 and 7 will be displayed.

+16
source share

If you're interested, the opposite of this is called Intersection

 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); } 
+1
source share

All Articles