2012-05-18 11 views
19

Na przykład, mam dwie tablice:uzyskać różne i wspólne elementy w dwóch tablicach z LINQ

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

Co usiłuję zrobić jest -

  1. Get wspólne elementy z list1 i list2 (np. { "2", "3", "4"})
  2. uzyskać różne elementy list1 i list2 (np. { "1", "5", "6",})
0.123.

Więc próbowałem z LINQ oraz -

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

ale

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

jakieś pomysły?

+1

To powinno działać. 'list1.Intersect (list2)' zwraca "2", "3", "4". – nemesv

+0

Brakuje 2 "nowych" w składni. To się nie skompiluje. Użyj: 'var list2 = new string [] {" 2 "," 3 "," 4 "};' –

+0

Silly me. W rzeczywistości, Intersect działa, tylko że druga część, aby wyprowadzić tablicę do pola tekstowego, zepsuła się. Dziękuje wszystkim! –

Odpowiedz

21

Jakoś masz ten wynik z innego miejsca. (Być może jesteś wypisywanie zawartości listDIff pierwszy, i myślę, że to było z listCommon.) Metoda Intersectrobi daje przedmiotów, które istnieje w obu listach:

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

wyjściowa:

2 
3 
4 
Powiązane problemy