Naor
Naor

Reputation: 24093

collect all array items from each object

I have 2 entities:

class A {
    ...
}
class B {
    IEnumerable<B> bs;
}

I have array of A's and I need to get all the B's in one IEnumerable. I can do:

IEnumerable<A> as=....;

IEnumerable<IEnumerable<B>> bss=as.Select(x=>x.bs);

IEnumerable<B> all=null;
foreach (IEnumerable<B> bs is bss) {
    if (all==null) { all=bs; }
    else { all=all.Contact(bs); }
}

I want to know if there is shorter way to do this.

Thanks

Upvotes: 0

Views: 83

Answers (4)

Jim Wooley
Jim Wooley

Reputation: 10408

Are you wanting SelectMany to flatten the B's?

IEnumerable<B> allBs = as.SelectMany(a => a.bs);

or using LINQ expressions:

IEnumerable<B> allBs = from a in as
                       from b in a.bs
                       select b;

Upvotes: 0

SLaks
SLaks

Reputation: 887777

Use the SelectMany method to flatten a single level of nesting:

all = as.SelectMany(a => a.bs);

Upvotes: 0

Matthew Abbott
Matthew Abbott

Reputation: 61599

Use SelectMany:

foreach (var b in allAs.SelectMany(a => a.Bs))
{
    // Do work here
}

Upvotes: 0

Random Dev
Random Dev

Reputation: 52290

You can Use SelectMany that will concatenate all the IEnumerables together

var all = as.SelectMany(a => a.bs);

Upvotes: 3

Related Questions