Linq列表中的列表转换为单个列表

257

看起来这种问题早就有答案了,但我找不到它。

我的问题很简单,如何用一条语句完成这个操作,以便不必创建空列表,然后在下一行聚合,而是可以有一个单独的LINQ语句输出我的最终列表。details是包含住所列表的项目列表,我只想要所有住所的平面列表。

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

4个回答

411
你想要使用 SelectMany 扩展方法。
var residences = details.SelectMany(d => d.AppForm_Residences).ToList();

3
谢谢。@JaredPar 选择了错误的元素,但是感谢你们两个的指导。 - Jarrett Widman

67
使用SelectMany。
var all = residences.SelectMany(x => x.AppForm_Residences);

53

这是一个样例代码:

List<int> listA = new List<int> { 1, 2, 3, 4, 5, 6 };

List<int> listB = new List<int> { 11, 12, 13, 14, 15, 16 };

List<List<int>> listOfLists = new List<List<int>> { listA, listB };

List<int> flattenedList = listOfLists.SelectMany(d => d).ToList();

foreach (int item in flattenedList)
{
    Console.WriteLine(item);
}

输出结果将是:

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

35

对于那些想要使用查询表达式语法的人:您需要使用两个from语句。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接