2010-01-14 12 views
6

Mam następujące klasyLINQ: Jak dołączyć wykaz elementów do innej listy

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

Biorąc pod uwagę List<Element>, jak znaleźć listę wszystkich Ints wewnątrz List<Element> przy użyciu LINQ?

mogę użyć następującego kodu

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

Ale to jest tak brzydki i długo zdyszany, że chcę wymiotować za każdym razem pisać.

Wszelkie pomysły?

Odpowiedz

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

lub może po prostu:

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

btw, prawdopodobnie będziesz chciał do zainicjowania listę:

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

Czy istnieje powód użyłeś "nową listę (x)" zamiast "x.ToList()"? –

+1

@Andrew nie specjalnie; albo działa, itp –

3

można po prostu użyć SelectMany aby uzyskać spłaszczyć List<int>:

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

... lub agregowania:

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