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

5
我有以下的类:
public class Element
{
  public List<int> Ints
  {
     get;private set;
  }
}

如果给定一个List<Element>,如何使用LINQ查找List<Element>中所有Ints的列表?

我可以使用以下代码:

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

但是它太丑陋和冗长,每次写它都想吐。 有什么好的建议吗?
3个回答

10
return (from el in elements
        from i in el.Ints
        select i).ToList();

或者只需:

return new List<int>(elements.SelectMany(el => el.Ints));

顺便提一下,你可能想要初始化这个列表:

public Element() {
    Ints = new List<int>();
}

你使用 "new List<int>(x)" 而不是 "x.ToList()" 有什么原因吗? - Andrew Coonce

3

您可以简单地使用 SelectMany 来获取平展的 List<int>

public static List<int> FindInts(List<Element> elements)
{
    return elements.SelectMany(e => e.Ints).ToList();
}

0

...或聚合:

List<Elements> elements = ... // Populate    
List<int> intsList = elements.Aggregate(Enumerable.Empty<int>(), (ints, elem) => ints.Concat(elem.Ints)).ToList(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接