2017-08-05 17 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(); 
相關問題