使用 Linq 展平 C# 列表字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9420582/
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
Flatten a C# Dictionary of Lists with Linq
提问by Paul
I have a Dictionary in C#:
我在 C# 中有一个字典:
Dictionary<string, List<string>>
How can I use Linq to flatten this into one List<string>that contains all of the lists in the Dictionary?
如何使用 Linq 将其展平为List<string>包含词典中所有列表的列表?
Thanks!
谢谢!
采纳答案by Jon Skeet
Very easily:
非常简单地:
var list = dictionary.Values // To get just the List<string>s
.SelectMany(x => x) // Flatten
.ToList(); // Listify
Here the SelectManycall takes a sequence of inputs (the lists which make the values of the dictionary) and projects each single input into another sequence of outputs - in this case "the elements of the list". It then flattens that sequence of sequences into a single sequence.
此处SelectMany调用采用输入序列(构成字典值的列表)并将每个输入投影到另一个输出序列中——在本例中为“列表的元素”。然后它将该序列序列展平为单个序列。
回答by porges
SelectManyis the easiest way to flatten things:
SelectMany是展平事物的最简单方法:
Dictionary.Values.SelectMany(x => x).ToList()
回答by zmbq
You should try something like this:
你应该尝试这样的事情:
dict.Values.Aggregate(new List<String>(), (a, b) => a.Concat(b));
回答by Julien May
Assuming you have an instance called dict:
假设您有一个名为 dict 的实例:
dict.SelectMany(pair => pair.Value.Select(str => str));
回答by Keith Nicholas
as a query
作为查询
var flattened = from p in dictionary
from s in p.Value
select s;
or as methods...
或者作为方法...
var flattened = dictionary.SelectMany(p => p.Value);
I like this over what others have done as I'm passing the whole dictionary into the Linq query rather than just the values.
我喜欢这一点而不是其他人所做的,因为我将整个字典传递到 Linq 查询中,而不仅仅是值。

