Merge Lists and return only duplicates

Say I've got two lists:

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

I want to merge these two lists and return another list with only the duplicates in the 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 will be the best shot. However, I haven't quite figured that since I have poor LINQ experience.

Upvotes: 4

Views: 1902

Answers (3)

Nemanja Boric
Nemanja Boric

Reputation: 22157

Use intersection:

var res = lst1.Intersect(lst2);

Upvotes: 1

Thelonias
Thelonias

Reputation: 2935

You want an "Intersect" of the two sets.

dupes = foo.Intersect(bar);

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190897

Intersect is what you want which is part of LINQ.

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

Ensure you have the System.Linq namespace referenced in your file.

Upvotes: 16

Related Questions