本文介绍了如何展平字典< string,List< string>>在linq中并保留结果中的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在linq中实现以下目标?我觉得应该有一个Linq替代方案.
How do you achieve the following in linq? I feel there should be a Linq alternative.
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
谢谢
推荐答案
您可以使用 SelectMany
扩展方法:
You can use SelectMany
extension method:
var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
.ToList();
这篇关于如何展平字典< string,List< string>>在linq中并保留结果中的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!