views:

89

answers:

4

I have problem when trying to convert dictionary to list.

Example if I have dictionary with template string as key and string as value. Then i wish to convert dictionary key to list collection as 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(??????);

Please help thx.

Regard

+1  A: 

If you want to use Linq then you can use the following snippet:

var listNumber = dicNumber.Keys.ToList();
Pop Catalin
+6  A: 

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();
Justin Niessner
@Brian - I was getting there in my edit. I wanted to show the select method first since that was what the OP asked about and then show the alternative. :-)
Justin Niessner
So I figured, so I removed my comment.
Brian Rasmussen
A: 
foreach ( var item in dicNumber) 
{

     listnumber.Add (item.Key);

 }
mumtaz
A: 

Alternatively:

var keys = new List<string>(dicNumber.Keys);
Stuart Dunkeld