MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Linq for nested loop

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)

Upvotes: 17

Views: 13716

Answers (3)

Tormod
Tormod

Reputation: 4573

There is an overload of SelectMany which allows access to the "parent" element. ListOfList.SelectMany(list=>list.InnerList,(lst,element)=> HandleInnerListAndElementFromIt(lst,element))

 result = myColl.SelectMany(x => x.MyList,(x1,x2)=>DoSomething(x1,x2));

EDIT Added:

For your concrete example it looks like this:

result = myColl.SelectMany(x=>x.MyList,(x,y)=>x.MyKey+y));

Notice that there are two lambda parameters to the SelectMany method call.

First lambda will take the "x" and return a new Enumerable. x=>x.MyList

The second lambda takes the "x" and "y" and produce a new result. (x,y)=>x.MyKey+y

Upvotes: 5

usr
usr

Reputation: 171178

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).

Upvotes: 21

juharr
juharr

Reputation: 32266

This is when I personally prefer query syntax

var result = from x in myCol1
             from y in x.MyList
             select x.MyKey + y;

Upvotes: 5

Related Questions