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开发者_Python百科 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
You can Use SelectMany that will concatenate all the IEnumerables together
var all = as.SelectMany(a => a.bs);
Use SelectMany
:
foreach (var b in allAs.SelectMany(a => a.Bs))
{
// Do work here
}
Use the SelectMany
method to flatten a single level of nesting:
all = as.SelectMany(a => a.bs);
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;
精彩评论