C# 在 LINQ 中展平列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1590723/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:06:49  来源:igfitidea点击:

Flatten List in LINQ

c#linqlist

提问by Cédric Boivin

I have a LINQ query which returns IEnumerable<List<int>>but i want to return only List<int>so i want to merge all my record in my IEnumerable<List<int>>to only one array.

我有一个 LINQ 查询返回IEnumerable<List<int>>但我只想返回List<int>所以我想将我的所有记录合并IEnumerable<List<int>>到一个数组中。

Example :

例子 :

IEnumerable<List<int>> iList = from number in
    (from no in Method() select no) select number;

I want to take all my result IEnumerable<List<int>>to only one List<int>

我想把我所有的结果都IEnumerable<List<int>>变成一个List<int>

Hence, from source arrays: [1,2,3,4] and [5,6,7]

因此,从源数组:[1,2,3,4] 和 [5,6,7]

I want only one array [1,2,3,4,5,6,7]

我只想要一个数组 [1,2,3,4,5,6,7]

Thanks

谢谢

采纳答案by Mike Two

Try SelectMany()

尝试 SelectMany()

var result = iList.SelectMany( i => i );

回答by mqp

Like this?

像这样?

var iList = Method().SelectMany(n => n);

回答by Daniel

If you have a List<List<int>> kyou can do

如果你有List<List<int>> k你可以做的

List<int> flatList= k.SelectMany( v => v).ToList();

回答by Dylan Beattie

iList.SelectMany(x => x).ToArray()

回答by recursive

With query syntax:

使用查询语法:

var values =
from inner in outer
from value in inner
select value;