列表<int>的Lambda Projection到SelectList </int>

时间:2013-05-30 16:18:48

标签: 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

实现这一目标的最佳方法是什么?

我需要:

Text Value
0    0
2    2
4    4
1    1

谢谢!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

试试这个简单的方法

IList<ServiceByContracts> serviceByContractList = new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().ToList();
 public SelectList ContractOptions = new SelectList(serviceByContractList , "YourColumnIdName", "ColoumTextName");

<强>更新

YourColumnIdName表示您的ServiceByContracts表主键ID列名称和ColoumTextName是您想要的ServiceByContracts表文本列名称...

答案 2 :(得分:0)

public SelectList ContractOptions = new SelectList(new Proposals().ServiceByContracts.Select(x => (int)x.ContractLength).Distinct().Select( d=>new {Text = d,Value =d}).ToList(),"Text","Value");

好的..我知道Robert McKee有类似的方法,因为我自己想出来了。我可以发表自己的答案!

为了成为一项好运动,我给了他答案!