List<MyParentClass> parents = new List<MyParentClass>();
var parent1 = new MyParentClass("parent1");
var parent2 = new MyParentClass("parent2");
parents.Add(parent1);
parents.Add(parent2);
var child1 = new MyChildClass("child1");
parent1.children.Add(child1);
var child2 = new MyChildClass("child2");
var child3 = new MyChildClass("child3");
parent2.children.Add(child2);
parent2.children.Add(child3);
var foo = from p in parents
select from c in p.children
select c;
Assert.IsNotNull(foo);
Assert.AreEqual(3, foo.Count());
NUnit.Framework.AssertionException:
expected: <3>
but was: <2>
我想我正在回归IList,但我期待这三个孩子。我怎么做到的?
答案 0 :(得分:6)
我对查询语法并不过分自信,但我认为这会使子列表变得扁平化:
var foo = from p in parents
from c in p.children
select c;
使用扩展方法语法,它看起来像这样:
var foo = parents.SelectMany(p => p.children);
答案 1 :(得分:4)
您实际上正在返回IEnumerable&lt; IEnumerable&lt; MyChildClass&gt;&gt;。为了得到一个简单的IEnumerable&lt; MyChildClass&gt;你可以拨打以下电话
var bar = foo.SelectMany(x => x);