使用Linq展平C#列表

Pau*_*aul 39 c# linq

我在C#中有一个字典:

Dictionary<string, List<string>>
Run Code Online (Sandbox Code Playgroud)

如何使用Linq将其展平为List<string>包含字典中所有列表的内容?

谢谢!

Jon*_*eet 75

非常简单地:

var list = dictionary.Values              // To get just the List<string>s
                     .SelectMany(x => x)  // Flatten
                     .ToList();           // Listify
Run Code Online (Sandbox Code Playgroud)

这里的SelectMany调用采用一系列输入(产生字典值的列表)并将每个单个输入投影到另一个输出序列 - 在这种情况下是"列表的元素".然后它将该序列序列展平为单个序列.

  • @Paul我很想评论说"它选择了很多",但实际上就是这样.如果有一个可枚举(或可查询的)对象列举返回时仍更枚举对象,例如一个列表的列表或散列集的阵列等,其选择那些对象的元素.所以在这里,值是一个`ICollection <List <string >>`它返回一个`IEnumerable <string>`. (10认同)

Kei*_*las 11

作为查询

var flattened = from p in dictionary
                from s in p.Value
                select s;
Run Code Online (Sandbox Code Playgroud)

或作为方法......

var flattened = dictionary.SelectMany(p => p.Value);
Run Code Online (Sandbox Code Playgroud)

我比其他人所做的更喜欢这个,因为我将整个字典传递给Linq查询而不仅仅是值.


por*_*ges 6

SelectMany 扁平化是最简单的方法:

Dictionary.Values.SelectMany(x => x).ToList()
Run Code Online (Sandbox Code Playgroud)