使用LINQ从Dictionary获取键值组合

时间:2015-07-13 13:27:47

标签: c# linq dictionary

假设我有以下词典:

private Dictionary<string, IEnumerable<string>> dic = new Dictionary<string, IEnumerable<string>>();

//.....
dic.Add("abc", new string[] { "1", "2", "3" });
dic.Add("def", new string[] { "-", "!", ")" });

如何获得包含以下组合的IEnumerable<Tuple<string, string>>

{
     { "abc", "1" },
     { "abc", "2" },
     { "abc", "3" },
     { "def", "-" },
     { "def", "!" },
     { "def", ")" }
}

必须Tuple<string, string>,但它似乎更合适。

如果有的话,我正在寻找一个简单的LINQ解决方案。

我尝试了以下内容:

var comb = dic.Select(i => i.Value.Select(v => Tuple.Create<string, string>(i.Key, v)));

comb最终属于IEnumerable<IEnumerable<Tuple<string, string>>>类型。

3 个答案:

答案 0 :(得分:5)

您希望Enumerable.SelectMany使IEnumerable<IEnumerable<T>>

变得平坦
var comb = dic.SelectMany(i => i.Value.Select(
                               v => Tuple.Create(i.Key, v)));

哪个收益率:

enter image description here

答案 1 :(得分:3)

将您的第一个(最后执行)Select更改为SelectMany以折叠IEnumerables

var comb = dic.SelectMany(i => i.Value.Select(v => Tuple.Create(i.Key, v)));
//returns IEnumerable<Tuple<string, string>>

答案 2 :(得分:0)

此解决方案也使用SelectMany,但可能稍微更具可读性:

var pairs =
  from kvp in dictionary
  from val in kvp.Value
  select Tuple.Create<string, string>(kvp.Key, val)