Linq for nested loop

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


This is when I personally prefer query syntax

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

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

Tags:

C#

Linq