如何在 linq 中压平字典 <string,List<string>> 并将键保留在结果中
How to flatten a dictionary<string,List<string>> in linq and keep the key in the results
你是如何在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
谢谢
您可以使用SelectMany
扩展方法:
var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
.ToList();
var result = (from food in foods
from detail in food.Value
select new Tuple<string, string>(food.Key, detail)).ToList();
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中实现以下功能的?我觉得应该有一个 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
谢谢
您可以使用SelectMany
扩展方法:
var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
.ToList();
var result = (from food in foods
from detail in food.Value
select new Tuple<string, string>(food.Key, detail)).ToList();
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"}},
};