Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 864
atreeon Avatar asked Jan 21 '16 15:01

atreeon


2 Answers

You can use SelectMany extension method:

var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
                 .ToList();
like image 62
octavioccl Avatar answered Oct 12 '22 19:10

octavioccl


 var result = (from food in foods 
               from detail in food.Value 
               select new Tuple<string, string>(food.Key, detail)).ToList();
like image 29
Radin Gospodinov Avatar answered Oct 12 '22 19:10

Radin Gospodinov