atr*_*eon 7 c# linq dictionary flatten
你如何在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
Run Code Online (Sandbox Code Playgroud)
谢谢
oct*_*ccl 14
您可以使用SelectMany扩展方法:
var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
.ToList();
Run Code Online (Sandbox Code Playgroud)