gpt4 book ai didi

c# - 选择列表的字典键和值

转载 作者:IT王子 更新时间:2023-10-29 04:45:51 30 4
gpt4 key购买 nike

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 中。 IDName 是该特定对象 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给你 KeyValue属性。

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

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

关于c# - 选择列表的字典键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307443/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com