2009-07-17 145 views
137

似乎是這樣的事情已經被回答,但我無法找到它。Linq清單列表到單個列表

我的問題很簡單,我怎麼能在一個語句中這樣做,以便不必新建空的列表,然後在下一行中進行聚合,我可以有一個單一的linq語句輸出我的最終列表。詳細信息是每個包含住宅列表的項目列表,我只希望所有住宅都在一個平面列表中。

var residences = new List<DAL.AppForm_Residences>(); 
details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d)); 
+1

[如何將具有相同類型項目的列表的列表合併到單個項目列表中?](http://stackoverflow.com/questions/1191054/how-to-merge-a-list-of-列表與同一類型的項目到單一列表項) – Dzyann 2015-12-11 15:40:07

回答

202

您要使用的SelectMany擴展方法。

var residences = details.SelectMany(d => d.AppForm_Residences).ToList(); 
+2

謝謝。 @JaredPar從錯誤的元素中進行選擇,但是感謝您的指導。 – 2009-07-18 02:31:55

39

使用的SelectMany

var all = residences.SelectMany(x => x.AppForm_Residences); 
22

而對於那些想要查詢表達式語法:您使用兩個聲明

var residences = (from d in details from a in d.AppForm_Residences select a).ToList(); 
23

有對你是一個示例代碼:

List<List<int>> l = new List<List<int>>(); 

    List<int> a = new List<int>(); 
    a.Add(1); 
    a.Add(2); 
    a.Add(3); 
    a.Add(4); 
    a.Add(5); 
    a.Add(6); 
    List<int> b = new List<int>(); 
    b.Add(11); 
    b.Add(12); 
    b.Add(13); 
    b.Add(14); 
    b.Add(15); 
    b.Add(16); 

    l.Add(a); 
    l.Add(b); 

    var r = l.SelectMany(d => d).ToList(); 
    foreach(int i in r) 
    { 
     Console.WriteLine(i); 
    } 

和OUT放將是:

1 
2 
3 
4 
5 
6 
11 
12 
13 
14 
15 
16 
Press any key to continue . . . 
+0

這幫助我理解並應用於我的數據。喊。 – sobelito 2016-12-13 11:22:37