我在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调用采用一系列输入(产生字典值的列表)并将每个单个输入投影到另一个输出序列 - 在这种情况下是"列表的元素".然后它将该序列序列展平为单个序列.
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查询而不仅仅是值.
SelectMany 扁平化是最简单的方法:
Dictionary.Values.SelectMany(x => x).ToList()
Run Code Online (Sandbox Code Playgroud)