How to get values in a dictionary as a list in C#

If you have a dictionary with scalar entities, its is fairly straightforward to get either all the Keys or the Values as a list:

Let’s say we have:

Dictionary<string, string> MyDictionary

To get all the keys as a list:

MyDictionary.Keys.ToList()

To get all the values as a list:

MyDictionary.Values.ToList()

If you have a case where the values in the dictionary key-value pairs are in the form of a list, this will require flattening the multiple lists of values into one. Something like this can be done to get all the values as a flat list:

Let’s say we have:

Dictionary<string, List<string>> MyDictionary

Using LINQ:

MyDictionary.SelectMany(kvp => kvp.Value).ToList()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>