2009-07-17 147 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