Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Keys and Values to a Select List

Tags:

Dictionary<string,string> dict = new Dictionary<string,string>();       dict.add("a1", "Car");   dict.add("a2", "Van");   dict.add("a3", "Bus"); 

SelectList SelectList = new SelectList((IEnumerable)mylist, "ID", "Name", selectedValue); 

In above code I have put a list mylist to a SelectList. ID and Name are two properties of that particular object list(mylist).

Likewise I need to add the Dictionary to the SelectList.


Need to add the key of the dictionary to the data Value parameter -(ID position of above example) Need to add the value of the dictionary to the data text parameter -(Name position of the above example)

So please tell me a way to create a select list using this dictionary keys and values without creating a new class.

like image 580
Sameera Avatar asked Jan 23 '14 11:01

Sameera


People also ask

How to make dict keys into list?

To convert Python Dictionary keys to List, you can use dict. keys() method which returns a dict_keys object. This object can be iterated, and if you pass it to list() constructor, it returns a list object with dictionary keys as elements.

Can you use a list as a key for a dictionary?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

How do I get a list of values from a list of keys?

To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys] that iterates over each key in the list of keys and puts the associated value d[key] into the newly-created list.

How to Get key from list in Python?

You can get all the keys in the dictionary as a Python List. dict. keys() returns an iterable of type dict_keys() . You can convert this into a list using list() .


1 Answers

You could try:

SelectList SelectList = new SelectList((IEnumerable)dict, "Key", "Value", selectedValue); 

Dictionary<string, string> implements IEnumerable<KeyValuePair<string, string>>, and KeyValuePair gives you the Key and Value properties.

Be aware, however, that the order of items returned by enumerating a Dictionary<string,string> is not guaranteed. If you want a guaranteed order, you can do something like:

SelectList SelectList = new SelectList(dict.OrderBy(x => x.Value), "Key", "Value", selectedValue); 
like image 179
Joe Avatar answered Oct 06 '22 17:10

Joe