Mat*_*ero 4 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[] { "-", "!", ")" });
Run Code Online (Sandbox Code Playgroud)
如何获得IEnumerable<Tuple<string, string>>包含以下组合的内容:
{
{ "abc", "1" },
{ "abc", "2" },
{ "abc", "3" },
{ "def", "-" },
{ "def", "!" },
{ "def", ")" }
}
Run Code Online (Sandbox Code Playgroud)
它并不必须是一个Tuple<string, string>,但它似乎是更appropiate类型.
我正在寻找一个简单的LINQ解决方案,如果有的话.
我尝试过以下方法:
var comb = dic.Select(i => i.Value.Select(v => Tuple.Create<string, string>(i.Key, v)));
Run Code Online (Sandbox Code Playgroud)
但comb最终成为了类型IEnumerable<IEnumerable<Tuple<string, string>>>.
你想要Enumerable.SelectMany哪个会弄平你的IEnumerable<IEnumerable<T>>:
var comb = dic.SelectMany(i => i.Value.Select(
v => Tuple.Create(i.Key, v)));
Run Code Online (Sandbox Code Playgroud)
产量:

| 归档时间: |
|
| 查看次数: |
538 次 |
| 最近记录: |