c# - 使用linq查询时如何获取int数组的索引

标签 c# asp.net-mvc linq

我想在 MVC 中创建一个包含特定数字的下拉列表

所以在我的模型中我有一个属性:

public IEnumerable<SelectListItem> Quantities { get; set; }

在我的 Controller 中,我实例化了我的模型:

Quantities = from s in numbers
             select new SelectListItem { Text = s.ToString()}

numbers 是一个 int 数组,里面有 10 个数字。

这段代码可以工作,但问题是我无法从 's' 获取数组的值(索引)。

有谁知道我如何获得这个值?

最佳答案

这对于 LINQ 表达式来说是不可能的。您可以使用以下内容:

Quantities = numbers.Select((s, index) => new SelectListItem 
{ 
    Value = index.ToString(), 
    Text = s.ToString()
);

关于c# - 使用linq查询时如何获取int数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9149944/

相关文章:

c# - WebMatrix.WebData.WebSecurity - 如何仅通过 PasswordResetToken 获取用户名

asp.net-mvc - ASP.NET MVC : How much processing in the view & when to use helper methods?

c# - 大数字的 IsNumeric Helper 方法

c# - LINQ select 语句后的强类型新对象

c# - System.IO.Exception 错误 : "The requested operation cannot be performed on a file with a user-mapped section open."

c# - 创建自定义 AppDomain 并向其添加程序集

c# - 使用 UpdateModel() 时如何消除服务器端清理的重复代码?

c# - 我可以在单个语句中从集合中进行此 linq 语句迭代吗?

c# - 如何在多部分/表单数据请求的请求正文中记录文件内容

c# - 如何在不使用 Subject<T> 支持字段的情况下公开 IObservable<T> 属性