【问题标题】:Creating a select list from an array [duplicate]从数组创建选择列表[重复]
【发布时间】:2013-01-02 21:34:53
【问题描述】:

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

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

【问题讨论】:

标签: c# arrays linq list ienumerable


【解决方案1】:

使用重载的Enumerable.Select方法:

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

【讨论】:

  • 感谢您的参考。注意,Value 必须是字符串类型,所以Value = index.ToString() 是正确的
  • @Jeff 谢谢!修复了这个错误
【解决方案2】:

试试Enumerable.Select

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

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

【讨论】:

    【解决方案3】:

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

    调试器中的屏幕截图

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2015-10-16
      • 2016-12-21
      • 2016-10-21
      相关资源
      最近更新 更多