在LINQ中展平列表

时间:2009-10-19 19:48:22

标签: c# linq list

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

示例:

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

我想将所有结果IEnumerable<List<int>>仅用于List<int>

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

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

由于

5 个答案:

答案 0 :(得分:490)

尝试SelectMany()

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

答案 1 :(得分:79)

使用查询语法:

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

答案 2 :(得分:21)

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

答案 3 :(得分:11)

喜欢这个吗?

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

答案 4 :(得分:10)

如果您有List<List<int>> k,则可以

List<int> flatList= k.SelectMany( v => v).ToList();
相关问题