Arpit Gupta
Arpit Gupta

Reputation: 1277

LINQ - Get items of list1 that are present in list2 to list3

I have two List<int> say list1 and list2. Now I need to create a LINQ expression which should work in a way that for each item in list1, if it is available in list2 then store it in list3. For example, list1 contains {5, 10, 15} and list2 contains {3, 5, 15, 20}. Then with the help of LINQ, list3should contain {5,15}. What I tried is -

list3 = list1.Where(t1 => list2.Any(t2 => t1.Contains(t2))).ToArray();

Upvotes: 1

Views: 400

Answers (3)

grishma shah
grishma shah

Reputation: 45

list3 = (from p in list1 where list2.Contains(p) select p).ToList();

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

As like other answers stated, Intersect will be a fine option for you, But i would like to fix the error in your code, Actually you should performs .Contains operation in List2 not in elements of List2. One more thing you have to note is that, the LHS of the assignment operation is of type List<int> so you have to use .ToList() instead for .ToArray(). which means you have to wrote like this:

list3 = list1.Where(t1 => list2.Contains(t1)).ToList();

Or something like This:

list3 = list1.Where(t1 => list2.Any(x=> x == t1)).ToList();

Upvotes: 2

Jf Beaulac
Jf Beaulac

Reputation: 5246

list3 = list1.Intersect(list2).ToList();

Upvotes: 6

Related Questions