2013-01-02 69 views
2

可能重复:
how to find the index particular items in the list using linq?从阵列中创建一个选择列表

我想从一个字符串数组创建IEnumerable<SelectListItem>

string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; 

model.month = months 
     .Select(r => new SelectListItem{Text = r, Value = ???}); 

是否有此查询中访问其索引的方法吗?

+0

http://msdn.microsoft.com/en-us/library/bb534869.aspx –

回答

12

使用重载Enumerable.Select方法:

model.month = months 
    .Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()}); 
+1

谢谢你的参考。值得一提的是,'Value'必须是字符串类型,所以'Value = index.ToString()'是正确的 – Jeff

+0

@Jeff谢谢!修正了这个错误 –

4

尝试用Enumerable.Select

通过将元素的索引合并到 中,将序列的每个元素投影到新的表单中。

model.month = months 
     .Select((r, i) => new SelectListItem{Text = r, Value = i.ToString()}); 
1

杰夫这应该为您根据里拉摹贴

string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; 
var query = months.Select((r, index) => new { Text = r, Value = index }); 

的是什么样子的调试器

enter image description here

屏幕截图链接的例子工作