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.
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.
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.
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.
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() .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With