[英]Flatten a C# Dictionary of Lists with Linq
我在C#中有一個字典:
Dictionary<string, List<string>>
如何使用Linq將其展平為包含Dictionary中所有List<string>
?
謝謝!
非常簡單地:
var list = dictionary.Values // To get just the List<string>s
.SelectMany(x => x) // Flatten
.ToList(); // Listify
這里, SelectMany
調用采用一系列輸入(產生字典值的列表)並將每個單個輸入投影到另一個輸出序列中 - 在本例中為“列表的元素”。 然后它將該序列序列展平為單個序列。
作為查詢
var flattened = from p in dictionary
from s in p.Value
select s;
或作為方法......
var flattened = dictionary.SelectMany(p => p.Value);
我喜歡這個,因為我將整個字典傳遞給Linq查詢而不僅僅是值。
SelectMany
是壓扁事物的最簡單方法:
Dictionary.Values.SelectMany(x => x).ToList()
假設你有一個名為dict的實例:
dict.SelectMany(pair => pair.Value.Select(str => str));
你應該嘗試這樣的事情:
dict.Values.Aggregate(new List<String>(), (a, b) => a.Concat(b));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.