Alex Rivera | Logout

Compare two lists to search common items

Asked 2012-07-31T12:24:16.013
16
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5

How to get all elements from one list that are present also in second list?

In this case should be: 1, 4

I talk of course about method without foreach. Rather linq query

Edit
Report

1 Answer

54

You can use the Intersect method.

var result = one.Intersect(second);

Example:

void Main()
{
    List<int> one = new List<int>() {1, 3, 4, 6, 7};
    List<int> second = new List<int>() {1, 2, 4, 5};

    foreach(int r in one.Intersect(second))
        Console.WriteLine(r);
}

Output:

1
4

answered 2012-07-31T12:24:49.497

Your Answer