字典键和选择列表的值

Sam*_*era 18 c# asp.net-mvc

Dictionary<string,string> dict = new Dictionary<string,string>();    
  dict.add("a1", "Car");
  dict.add("a2", "Van");
  dict.add("a3", "Bus");
Run Code Online (Sandbox Code Playgroud)
SelectList SelectList = new SelectList((IEnumerable)mylist, "ID", "Name", selectedValue);
Run Code Online (Sandbox Code Playgroud)

在上面的代码我已经列出mylist了一个列表SelectList.ID并且Name是该特定对象的两个属性list(mylist).

同样我需要将词典添加到 SelectList.


需要在data Value参数中添加字典的键- (ID上例中的位置)需要将字典的值添加到data text参数中 - (Name上例的位置)

因此,请告诉我一种使用此字典键和值创建选择列表的方法,而无需创建新类.

Joe*_*Joe 35

你可以尝试:

SelectList SelectList = new SelectList((IEnumerable)dict, "Key", "Value", selectedValue);
Run Code Online (Sandbox Code Playgroud)

Dictionary<string, string>实现IEnumerable<KeyValuePair<string, string>>,并KeyValuePair为您提供KeyValue属性.

但请注意,枚举a返回的项目顺序Dictionary<string,string>无法保证.如果您想要保证订单,您可以执行以下操作:

SelectList SelectList = new SelectList(dict.OrderBy(x => x.Value), "Key", "Value", selectedValue);
Run Code Online (Sandbox Code Playgroud)


Kne*_*min 18

您真正需要做的就是将字典作为参数传递并使用重载:

public SelectList(IEnumerable items, string dataValueField, string dataTextField);
Run Code Online (Sandbox Code Playgroud)

例:

var dictionary = new Dictionary<string, string>
{
   {"a1", "Car"}, 
   {"a2", "Van"}, 
   {"a3", "Bus"}
};

var selectList = new SelectList(dictionary, "Key", "Value");
Run Code Online (Sandbox Code Playgroud)

我知道这篇文章有点陈旧但我来这里是为了找到答案,并根据之前给出的答案得出了这个结论.