【问题标题】:How to flatten a dictionary<string,List<string>> in linq and keep the key in the results如何在 linq 中展平字典<string,List<string>> 并在结果中保留键
【发布时间】: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

谢谢

【问题讨论】:

    标签: c# linq dictionary flatten


    【解决方案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"}},
                    };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-20
          • 2012-12-30
          相关资源
          最近更新 更多