使用LINQ从字典中获取键值对组合

4

假设我有以下字典:

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个回答

5
你需要使用 Enumerable.SelectMany,这个方法可以将你的 IEnumerable<IEnumerable<T>> 扁平化:
var comb = dic.SelectMany(i => i.Value.Select(
                               v => Tuple.Create(i.Key, v)));

这将产生: enter image description here

3

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

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

1

这个解决方案也使用了SelectMany,但可能更易读:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接