LINQ:如何将元素列表附加到另一个列表中

Gra*_*ton 6 c# linq

我有以下课程

public class Element
{
  public List<int> Ints
  {
     get;private set;
  }
}
Run Code Online (Sandbox Code Playgroud)

给定a List<Element>,如何查找使用LINQ 的所有Ints内部列表List<Element>

我可以使用以下代码

public static List<int> FindInts(List<Element> elements)
{
 var ints = new List<int>();
 foreach(var element in elements)
 {
  ints.AddRange(element.Ints);
 }
 return ints;
 }
}
Run Code Online (Sandbox Code Playgroud)

但它是如此丑陋和冗长的啰嗦,我想每次写作都呕吐.

有任何想法吗?

Mar*_*ell 10

return (from el in elements
        from i in el.Ints
        select i).ToList();
Run Code Online (Sandbox Code Playgroud)

或者只是:

return new List<int>(elements.SelectMany(el => el.Ints));
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你可能想要初始化列表:

public Element() {
    Ints = new List<int>();
}
Run Code Online (Sandbox Code Playgroud)