简体   繁体   中英

List Of Dictionary to List of List<string> in LINQ

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?

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:

在此处输入图像描述

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

You can try like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM