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);
在上面的代码中,我将一个列表 mylist
放到了一个 SelectList
中。 ID
和 Name
是该特定对象 list(mylist)
的两个属性。
同样,我需要将字典添加到 SelectList。
需要在data Value
参数中加入字典的key -(上例的ID
位置)
需要在data text
参数中加入字典的值-(上例的Name
位置)
因此,请告诉我一种无需创建新类即可使用此字典键和值创建选择列表的方法。
最佳答案
你可以试试:
SelectList SelectList = new SelectList((IEnumerable)dict, "Key", "Value", selectedValue);
Dictionary<string, string>
工具 IEnumerable<KeyValuePair<string, string>>
, 和 KeyValuePair
给你 Key
和 Value
属性。
但是请注意,通过枚举 Dictionary<string,string>
返回的项目顺序不能保证。如果您想要有保证的订单,您可以执行以下操作:
SelectList SelectList = new SelectList(dict.OrderBy(x => x.Value), "Key", "Value", selectedValue);
关于c# - 选择列表的字典键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307443/