如何在 linq 中展平字典<string,List<string>> 并在结果中保留键
Posted
技术标签:
【中文标题】如何在 linq 中展平字典<string,List<string>> 并在结果中保留键【英文标题】:How to flatten a dictionary<string,List<string>> in linq and keep the key in the results 【发布时间】:2016-04-27 22:15:41 【问题描述】:你如何在 linq 中实现以下目标?我觉得应该有一个 Linq 替代方案。
var foods = new Dictionary<string, List<string>>();
foods.Add("Cake", new List<string>() "Sponge", "Gateux", "Tart" );
foods.Add("Pie", new List<string>() "Mud", "Apple" );
foods.Add("Roll", new List<string>() "Sausage" );
var result = new List<Tuple<string, string>>();
foreach (var food in foods)
foreach (var detail in food.Value)
result.Add(new Tuple<string, string>(food.Key, detail));
ie
cake <sponge, gateux>
pie <apple>
to
cake, sponge
cake, gateux
pie, apple
谢谢
【问题讨论】:
【参考方案1】:你可以使用SelectMany
扩展方法:
var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
.ToList();
【讨论】:
【参考方案2】: var result = (from food in foods
from detail in food.Value
select new Tuple<string, string>(food.Key, detail)).ToList();
【讨论】:
【参考方案3】:Linq 是一个查询。这就是“q”的含义。您正在将项目添加到字典中。试试这个
Dictionary<string, List<string>> foods = new Dictionary<string, List<string>>()
"cake", new List<string>() "Sponge", "Gateux", "Tart",
"Pie", new List<string>() "Mud", "Apple",
"Roll", new List<string>() "Sausage",
;
【讨论】:
以上是关于如何在 linq 中展平字典<string,List<string>> 并在结果中保留键的主要内容,如果未能解决你的问题,请参考以下文章