字典键值,以选择列表 [英] Dictionary Keys and Values to a Select List

查看:170
本文介绍了字典键值,以选择列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

在上面code我已经把名单MYLIST来选择列表。 ID和名称是特定对象的列表(MYLIST)的两个属性。
同样,我需要将字典添加到选择列表。
**
需要字典的键添加到数据值的参数 - (上面的例子中的ID位置)
需要字典的值添加到数据文参数 - (上面的例子中的姓名的位置)

in above code I have put a list "mylist" to a Select list. ID and Name are two properties of that particular object list(mylist). Likewise I need to add the Dictionary to the Select List. ** 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.

推荐答案

您可以尝试:

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

词典&LT;字符串,字符串&GT; 工具的IEnumerable&LT; KeyValuePair&LT;字符串,字符串&GT;&GT; KeyValuePair <​​/ code>为您提供属性。

请注意,但是,项目的顺序通过枚举词典&LT返回;字符串,字符串&GT; 无法得到保证。如果你想有一个保证的顺序,你可以这样做:

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);

这篇关于字典键值,以选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆