Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq for nested loop

Tags:

c#

linq

I have a loop as follows:

foreach(x in myColl) 
{
    foreach(var y in x.MyList) 
    {
        result.Add(x.MyKey + y)
    }
}

That means within my inner loop I need access to a property of the current outer element.

I´m looking for a LINQ-statement but I´m unsure on it. I tried it by using

result = myColl
    .SelectMany(x => x.MyList)
    .SelectMany(x => /* how to get the key of the outer loop here */ + x)
like image 287
MakePeaceGreatAgain Avatar asked Jan 29 '16 13:01

MakePeaceGreatAgain


1 Answers

This is easy with query expressions:

(from x in myColl
 from y in x.MyList
 select x.MyKey + y).ToList()

This works because this translates to:

myColl
.SelectMany(x => x.MyList.Select(item => new { List = x, Item = item }))
.Select(x => ...) //rest of the query, whatever you like

The key is to keep both the list as well as the list items. Channel them through the query using an anonymous type (or any other container).

like image 173
usr Avatar answered Sep 23 '22 00:09

usr