Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary to list collection in C#

I have a problem when trying to convert a dictionary to list.

Example if I have a dictionary with template string as key and string as value. Then I wish to convert the dictionary key to list collection as a string.

Dictionary<string, string> dicNumber = new Dictionary<string, string>(); List<string> listNumber = new List<string>();  dicNumber.Add("1", "First"); dicNumber.Add("2", "Second"); dicNumber.Add("3", "Third");  // So the code may something look like this //listNumber = dicNumber.Select(??????); 
like image 935
Edy Cu Avatar asked Oct 19 '10 12:10

Edy Cu


People also ask

How to convert dict to list in c#?

ToList(); List<string> values = keys. Select(i => dicNumber[i]). ToList();

Can we convert dictionary to list in Python?

Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.


2 Answers

To convert the Keys to a List of their own:

listNumber = dicNumber.Select(kvp => kvp.Key).ToList(); 

Or you can shorten it up and not even bother using select:

listNumber = dicNumber.Keys.ToList(); 
like image 141
Justin Niessner Avatar answered Sep 22 '22 05:09

Justin Niessner


Alternatively:

var keys = new List<string>(dicNumber.Keys); 
like image 26
stuartd Avatar answered Sep 21 '22 05:09

stuartd