Asp.net mvc 列表的Lambda投影<;int>;选择列表
我投影以下整数列表,并将获得我的Asp.net mvc 列表的Lambda投影<;int>;选择列表,asp.net-mvc,Asp.net Mvc,我投影以下整数列表,并将获得我的SelectList: public SelectList ContractOptions = new SelectList(new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().ToList()); 我的结果是: Text Value 0 null 2 null 4 null 1 null 实现这一目标的最佳方法是
SelectList
:
public SelectList ContractOptions = new SelectList(new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().ToList());
我的结果是:
Text Value
0 null
2 null
4 null
1 null
实现这一目标的最佳方法是什么
我需要:
Text Value
0 0
2 2
4 4
1 1
谢谢 试试这个简单的方法
IList<ServiceByContracts> serviceByContractList = new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().ToList();
public SelectList ContractOptions = new SelectList(serviceByContractList , "YourColumnIdName", "ColoumTextName");
IList serviceByContractList=new Propositions().ServiceByContracts.Select(x=>(int)x.ContractLength.Distinct().ToList();
public SelectList ContractOptions=新建SelectList(serviceByContractList、“YourColumnId名称”、“ColumTextName”);
更新
YourColumnIdName
表示ServiceByContracts表主键Id列名,ColoumTextName
是您想要的ServiceByContracts表文本列名
public SelectList ContractOptions = new SelectList(
new Proposals()
.ServiceByContracts
.Select(x => (int)x.ContractLength)
.Distinct()
.Select(x=>new{Text=x.ContractLength.ToString(),Value=x.ContractLength.ToString()}),
"Text","Value");
您也可以尝试:
public SelectList ContractOptions = new SelectList(
new Proposals()
.ServiceByContracts
.Select(x => x.ContractLength.ToString())
.Distinct(),
"ContractLength","ContractLength");
好的。。我知道罗伯特·麦基(Robert McKee)也有类似的方法,因为这是我自己想出来的。我可以发布我自己的答案
为了好玩,我给了他答案 这将在运行时崩溃,原因如下:
{“数据绑定:'System.Int32'不包含名为'YourColumnIdName'的属性。”
嘿,该名称表示您的ServiceByContracts表主键Id列名,而ColumTextName是您想要的ServiceByContracts表文本列名……最好自己找到它。这样你会学到更多。
public SelectList ContractOptions = new SelectList(new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().Select( d=>new {Text = d,Value =d}).ToList(),"Text","Value");