Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify conventional foreach nested loop using linq & lambda expression

(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);
                }
            }
        }
like image 363
MagB Avatar asked Nov 28 '22 02:11

MagB


2 Answers

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));
like image 145
Anirudha Avatar answered Dec 05 '22 03:12

Anirudha


coll3 = coll1.Where(i => coll2.Contains(i)).ToList();

Update. A little bit simpler, as suggested in comments:

coll3 = coll1.Where(coll2.Contains).ToList();
like image 27
Andrei Avatar answered Dec 05 '22 03:12

Andrei