2017-08-05 42 views
0

我想扁平化(取消组合)我的字典 - 并尝试如果它可以由Linq完成。Dictionary <something,List <>> flatten(ungroup)以列表的东西和列表中的元素 - C#

样品输入:

Dictionary<int, List<string>> dict = new Dictionary<int, System.Collections.Generic.List<string>>(); 
dict.Add(0, new List<string>() { "a", "b" }); 
dict.Add(1, new List<string>() { "c", "d"}); 

我想要实现的是以下元素的列表:

0A

0B

1C

1D

当然

这是可以做到的:

List<string> output = new List<string>(); 
foreach (var element in dict) 
{ 
    foreach (var valuesElement in element.Value) 
    { 
     output.Add(element.Key + valuesElement); 
    } 
} 

我只是在寻找是否有任何“聪明” LINQ建设来实现它。

回答

2

您正在寻找.SelectMany()

dict.SelectMany(x => x.Value.Select(y => $"{x.Key}{y}")); 

Here's更多解释它是如何工作的。

3

的字典和构建的键值对基于价值的项目使用SelectMany

Dictionary<int, List<string>> dict = new Dictionary<int, System.Collections.Generic.List<string>>(); 
dict.Add(0, new List<string>() { "a", "b" }); 
dict.Add(1, new List<string>() { "c", "d" }); 

List<string> output = dict.SelectMany(kvp => kvp.Value.Select(v => string.Format("{0}{1}", kvp.Key, v))).ToList(); 
相关问题