可能重复:
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 :(得分:13)
使用重载Enumerable.Select方法:
model.month = months
.Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()});
答案 1 :(得分:5)
尝试使用Enumerable.Select
。
通过合并将序列的每个元素投影到新表单中 元素的索引。
model.month = months
.Select((r, i) => new SelectListItem{Text = r, Value = i.ToString()});
答案 2 :(得分:1)
根据lila G发布的链接上的示例
,Jeff应该适合您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 });
调试器中的外观屏幕截图