2

可能重复:
如何使用 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 = ???});

有没有办法在这个查询中访问他们的索引?

4

3 回答 3

13

使用重载的 Enumerable.Select方法:

model.month = months
    .Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()});
于 2013-01-02T21:36:10.120 回答
5

尝试使用Enumerable.Select.

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

model.month = months
        .Select((r, i) => new SelectListItem{Text = r, Value = i.ToString()});
于 2013-01-02T21:38:22.833 回答
2

杰夫,根据 lila G 发布的链接上的示例,这应该对您有用

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

调试器中的屏幕截图

在此处输入图像描述

于 2013-01-02T21:43:29.090 回答