开发者

LINQ: How to Append List of Elements Into Another List

开发者 https://www.devze.com 2022-12-16 03:30 出处:网络
I have the following class public class Element { public List<int> Ints { get;private set; } } Given a List<Element>, how to find a list of all the Ints inside the List<Element> u

I have the following class

public class Element
{
  public List<int> Ints
  {
     get;private set;
  }
}

Given a List<Element>, how to find a list of all the Ints inside the List<Element> using LINQ?

I can use the following code

public static List<int&g开发者_Go百科t; FindInts(List<Element> elements)
{
 var ints = new List<int>();
 foreach(var element in elements)
 {
  ints.AddRange(element.Ints);
 }
 return ints;
 }
}

But it is so ugly and long winded that I want to vomit every time I write it.

Any ideas?


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

or maybe just:

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

btw, you'll probably want to initialise the list:

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


You can simply use SelectMany to get a flatten List<int>:

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


... or aggregating:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号