我有两个实体:
class A {
...
}
class B {
IEnumerable<B> bs;
}
我有A的数组,我需要在一个IEnumerable中获得所有的B。我能做到:
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); }
}
我想知道是否有更短的方法来做到这一点。
由于
答案 0 :(得分:3)
您可以使用将所有IEnumerables连接在一起的SelectMany
var all = as.SelectMany(a => a.bs);
答案 1 :(得分:0)
使用SelectMany
方法展平单层嵌套:
all = as.SelectMany(a => a.bs);
答案 2 :(得分:0)
使用SelectMany
:
foreach (var b in allAs.SelectMany(a => a.Bs))
{
// Do work here
}
答案 3 :(得分:0)
你想让SelectMany压扁B吗?
IEnumerable<B> allBs = as.SelectMany(a => a.bs);
或使用LINQ表达式:
IEnumerable<B> allBs = from a in as
from b in a.bs
select b;