(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);
}
}
}
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));
coll3 = coll1.Where(i => coll2.Contains(i)).ToList();
Update. A little bit simpler, as suggested in comments:
coll3 = coll1.Where(coll2.Contains).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With