C# Linq 选择 IList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/632521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq Select IList
提问by Jason Marcell
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>
I think I'm getting an IList of ILists back, but I exepect just the three children. How do I get that?
我想我得到了一个 IList 的 IList,但我只希望三个孩子。我怎么得到它?
采纳答案by Matt Hamilton
I'm not overly confident with the query syntax, but I think this will flatten out the list of children:
我对查询语法并不过分自信,但我认为这会使子项列表变平:
var foo = from p in parents
from c in p.children
select c;
Using the extension-method syntax it looks like this:
使用扩展方法语法,它看起来像这样:
var foo = parents.SelectMany(p => p.children);
回答by JaredPar
You are actually getting back an IEnumerable<IEnumerable<MyChildClass>>. In order to get a simple IEnumerable<MyChildClass> you can make the following call
你实际上是在找回一个 IEnumerable<IEnumerable<MyChildClass>>。为了获得一个简单的 IEnumerable<MyChildClass> 你可以进行以下调用
var bar = foo.SelectMany(x => x);