Simplify conventional foreach nested loop using linq & lambda expression

c#, lambda, linq, nested-loops

Solution

You can use Intersect

coll1.Intersect(coll2);

But this wont work as expected(see King King's comment)..You can instead do this

coll2.Where(x=>coll1.Any(y=>x==y));

Problem

(See my code snippet below) I want to find all items of coll1 that matched to items of coll2 (number of items of coll2 <= number of items of coll1) and put the query result in coll3. How to achieve it using linq and lambda expression? Surely, I can simply copy coll2 to coll3 :-) but that is not my goal. I want to know the ways using linq and lambda to replace such conventional logic construct. Thank you in advance. ``` var coll1 = new List<int>() { 1, 2, 3, 4, 5 }; var coll2 = new List<int>() { 2, 4 }; var coll3 = new List<int>(); foreach ( var selected in coll2 ) { foreach ( var item in coll1 ) { if ( selected == item ) { coll3.Add(item); } } } ```

Original source