Merge lists and return only duplicates

Let's say I have two lists:

List<string>foo=new List<string>(); List<string>bar=new List<string>(); 

I want to combine these two lists and return another list with only duplicates in both.
So, if I have:

 //pseudocode foo={"baz","lemons","somethingelse"} bar={"what","another","baz","somethingelse","kitten"} 

I want it to return a new list:

 //pseudocode dupes={"baz","somethingelse"} 

I think using LINQ would be a better hit. However, I did not quite understand that, since I have poor LINQ experience.

+4
source share
3 answers

Intersect is what you want, being part of LINQ.

 dupes = foo.Intersect(bar).ToList(); 

Make sure your System.Linq namespace is specified in your file.

+17
source

You want the "Intersection" of two sets.

 dupes = foo.Intersect(bar); 
+3
source

Use the crossroads:

 var res = lst1.Intersect(lst2); 
+1
source

All Articles