Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: How to Append List of Elements Into Another List

Tags:

c#

linq

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> 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?

like image 764
Graviton Avatar asked Jan 14 '10 05:01

Graviton


2 Answers

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>();
}
like image 147
Marc Gravell Avatar answered Oct 04 '22 00:10

Marc Gravell


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();
}
like image 32
Christian C. Salvadó Avatar answered Oct 03 '22 23:10

Christian C. Salvadó