Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - operating on lists of lists

Tags:

c#

list

lambda

linq

I have a list of class A, class A contains a list of class B. I want to operate on all instances of B within all instances of class A.

var myListOfA = new List<A>();

class A
{
    public List<B> ListOfB;
}

How can I iterate over all B i.e. foreach(var b in myListOfA.ListOfB){}?

like image 272
Chris Avatar asked Sep 20 '11 13:09

Chris


2 Answers

You can use SelectMany:

foreach(var b in myListOfA.SelectMany(a => a.ListofB))

See it in action at ideone.com.

like image 162
Jens Avatar answered Sep 30 '22 15:09

Jens


another way that works well for how i think of nested objects is:

(from A objA in myListOfA
    from B objB in objA.ListOfB
        select objB);

this will "fan out" the list of b's within all the a's in the main list.

like image 25
Will Charczuk Avatar answered Sep 30 '22 17:09

Will Charczuk