假设我有以下词典:
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>>>
类型。
答案 0 :(得分:5)
您希望Enumerable.SelectMany
使IEnumerable<IEnumerable<T>>
:
var comb = dic.SelectMany(i => i.Value.Select(
v => Tuple.Create(i.Key, v)));
哪个收益率:
答案 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)