字典键和选择列表的值

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

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

在上面的代码中,我将列表mylist放入SelectListIDName是该特定对象list(mylist)两个属性。

同样,我需要将Dictionary添加到SelectList.


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

所以请告诉我一种使用这个字典键和值创建选择列表而不创建新类的方法。

你可以尝试:

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

Dictionary实现IEnumerable>KeyValuePair为您提供KeyValue属性。

但请注意,枚举Dictionary返回的项的顺序不能保证。 如果您想要保证订单,您可以执行以下操作:

 SelectList SelectList = new SelectList(dict.OrderBy(x => x.Value), "Key", "Value", selectedValue); 

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

 public SelectList(IEnumerable items, string dataValueField, string dataTextField); 

例:

 var dictionary = new Dictionary { {"a1", "Car"}, {"a2", "Van"}, {"a3", "Bus"} }; var selectList = new SelectList(dictionary, "Key", "Value"); 

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

您可以从Dictionary中构造一个SelectListItem对象列表,然后从中创建一个SelectList。

 var dict = new Dictionary { {"a1", "Car"}, {"a2", "Van"}, {"a3", "Bus"} }; var myListItems = new List(); myListItems.AddRange(dict.Select(keyValuePair => new SelectListItem() { Value = keyValuePair.Key, Text = keyValuePair.Value })); var myList = new SelectList(myListItems); 

我喜欢这样写:

 @Html.DropDownListFor(model => model.Delimiter, new Dictionary { {",", ", (Comma)"}, { ";", "; (Semicolon)"} }.Select(x => new SelectListItem {Value = x.Key, Text = x.Value})) 

因为这样,您不必依赖字符串"Key""Value"

尝试

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