2013-05-30 88 views
0

我项目中的以下整数的名单,我会得到我的SelectListLAMBDA投影到选择列表的

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 

谢谢!

回答

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

+1太棒了!非常感谢! – Pinch

+0

自己想出来总是更好。你更多地学习。 –

+0

啊,我的一天! – Pinch

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表中的文本列名...

+0

这会在运行时崩溃,类似于:{{“DataBinding:'System.Int32'不包含名为'YourColumnIdName'的属性。”}' –

+0

嘿,那个名字表示您的ServiceByContracts表的主键ID列名并且ColoumTextName是您想要的ServiceByContracts表文本列名称... – 2013-05-30 16:58:13

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

好吧..我知道罗伯特·麦基也有类似的做法,因为我想通了这一点我自己。我可以发布我自己的答案!

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