tags:

views:

720

answers:

4

How can I use Linq to find common items between 2 generic lists of type string.

For example, say I have the following code, I would like to get a List < string> which would contain item2 and item3:

List<string> List1 = new List<string>();
List<string> List2 = new List<string>();

List1.Add("item1");
List1.Add("item2");
List1.Add("item3");

List2.Add("item2");
List2.Add("item3");
List2.Add("item4");
+10  A: 
var items = List1.Intersect(List2);

see http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx, from the much recommended 101 LINQ Samples

Kobi
A: 
from item in list1
where list2.Contains(item)
select item

will work for valuetypes.

Rune FS
+4  A: 

I know LINQ was tagged, but just for completeness; if LINQ isn't an option;

List<string> result = list1.FindAll(list2.Contains);
Marc Gravell
+1  A: 

Hi

How about

var List3 = list1.Intersect(list2)

regards Edwards

Edwards
It seems large portions of your answer intersect with my answer.
Kobi