How to flatten a dictionary<string,List<string>> in linq and keep the key in the results

笑着哭i 提交于 2019-12-30 18:08:07

问题


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

thank you


回答1:


You can use SelectMany extension method:

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 is a query. That is what the 'q' stands for. You are adding items into a dictionary. Try this

            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"}},
            };


来源:https://stackoverflow.com/questions/34927634/how-to-flatten-a-dictionarystring-liststring-in-linq-and-keep-the-key-in-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!