如何在 linq 中展平字典<字符串,列表<字符串>>并将键保留在结果中

本文关键字:字符串 结果 保留 字典 linq 列表 | 更新日期: 2023-09-27 18:31:16

如何在 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

谢谢

如何在 linq 中展平字典<字符串,列表<字符串>>并将键保留在结果中

您可以使用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"}},
            };