Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get different and common items in two arrays with LINQ [closed]

Tags:

For example, I have two arrays:

var list1 = string[] {"1", "2", "3", "4", "5", "6"}; var list2 = string[] {"2", "3", "4"}; 

What I'm trying to do is -

  1. Get common items from list1 and list2 (eg. {"2", "3", "4"})
  2. Get different items list1 and list2 (eg. {"1", "5", "6"})

So I've tried with LINQ and -

var listDiff = list1.Except(list2); //This gets the desire result for different items 

But,

var listCommon = list1.Intersect(list2); //This doesn't give me desire result. Comes out as {"1", "5", "6", "2", "3", "4"}; 

Any ideas?

like image 276
Ye Myat Aung Avatar asked May 18 '12 07:05

Ye Myat Aung


Video Answer


1 Answers

Somehow you have got that result from somewhere else. (Perhaps you are writing out the contents of listDIff first, and thought that it was from listCommon.) The Intersect method does give you the items that exists in both lists:

var list1 = new string[] {"1", "2", "3", "4", "5", "6"}; var list2 = new string[] {"2", "3", "4"}; var listCommon = list1.Intersect(list2); foreach (string s in listCommon) Console.WriteLine(s); 

Output:

2 3 4 
like image 57
Guffa Avatar answered Oct 12 '22 11:10

Guffa