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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:06:15  来源:igfitidea点击:

Linq Select IList

c#linqilist

提问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);