C# Linq 列表到单个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1145558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq list of lists to single list
提问by Jarrett Widman
Seems like this is the kind of thing that would have already been answered but I'm unable to find it.
似乎这是一种已经得到回答的事情,但我无法找到它。
My question is pretty simple, how can I do this in one statement so that instead of having to new the empty list and then aggregate in the next line, that I can have a single linq statement that outputs my final list. details is a list of items that each contain a list of residences, I just want all of the residences in a flat list.
我的问题很简单,如何在一个语句中执行此操作,以便不必新建空列表然后在下一行聚合,而是可以使用单个 linq 语句来输出我的最终列表。details 是一个项目列表,每个项目都包含一个住宅列表,我只想要一个平面列表中的所有住宅。
var residences = new List<DAL.AppForm_Residences>();
details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d));
采纳答案by Noldorin
You want to use the SelectMany
extension method.
您想使用SelectMany
扩展方法。
var residences = details.SelectMany(d => d.AppForm_Residences).ToList();
回答by JaredPar
Use SelectMany
使用多选
var all = residences.SelectMany(x => x.AppForm_Residences);
回答by Sean B
And for those that want the query expression syntax: you use two fromstatements
对于那些想要查询表达式语法的人:您使用两个from语句
var residences = (from d in details from a in d.AppForm_Residences select a).ToList();
回答by Wilson Wu
Here is a sample code for you:
这是一个示例代码:
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);
}
And the out put will be:
输出将是:
1
2
3
4
5
6
11
12
13
14
15
16
Press any key to continue . . .