Home > front end >  List Of Dictionary to List of List<string> in LINQ
List Of Dictionary to List of List<string> in LINQ

Time:08-05

HI I have this example data which is in List<Dictionary<string,string>>

var menu = new List<Dictionary<string,string>> { new Dictionary<string, string> { { "Meal", "Pasta" }, { "Meal", "Pizza" } } , new Dictionary<string, string> { { "Entree", "Calamari Salad" } } },

I need to convert the above list to something like this

var menu = new List<List<string>> { new List<string> { "Meal:Pasta", "Meal:Pizza" }, new List<string> { "Entree:Calamari Salad" } };

how can I do this with LINQ query?

CodePudding user response:

First of all you will receive an exception, that "Meal" key already exist in dictionary.

Secondly, if you need to have the same types as you mentioned:

List<List<string>> result = menu.Select(m => m.Select(x => $"{x.Key}:{x.Value}").ToList()).ToList();

So result will looks like:

enter image description here

Please note, that I have replaced key and value for dictionary "Meal" to avoid receiving exeption about existing key.

CodePudding user response:

You can try like below.

var result = menu.Select(x => x.Select(y => $"{y.Key}:{y.Value}"));
  • Related