【问题标题】:IEnumerable.Select with indexIEnumerable.Select 带索引
【发布时间】:2014-12-04 02:06:41
【问题描述】:

我有以下代码:

 var accidents = text.Skip(NumberOfAccidentsLine + 1).Take(numberOfAccidentsInFile).ToArray();

其中的事故是一个字符串数组。

我想做一个从字符串数组到 Accident 对象数组的 Linq 转换,如下所示:

 return accidents.Select(t => new Accident() {Id = i, Name = t.Replace("\"", string.Empty)}).ToArray();

我如何使用 Linq 从事故数组中检索索引 i 还是我必须去老学校?

【问题讨论】:

  • 您想要来自accidents 数组本身的索引,还是来自原始text 枚举的索引?如果是前者,那么 Marcin 的回答很好。如果是后者,那么您需要在引入索引的初始Select() 之后执行Skip()Take()

标签: c# linq ienumerable


【解决方案1】:

我不确定您要查找哪种索引,但如果它只是一组连续数字,那么您很幸运。 Select 重载正是这样做的:

return accidents.Select((t, i) => new Accident() {Id = i, Name = t.Replace("\"", string.Empty)}).ToArray();

它需要一个接受两个参数的委托 - 项目及其索引。

【讨论】:

  • 我只需要一组连续的数字,谢谢。
【解决方案2】:

使用 Enumerable.Range 生成 ID 值,然后使用当前值索引到您的字符串数组:

Enumerable.Range(0, accidents.Length).Select(f => new Accident() { Id = f, Name = accidents[f] })

【讨论】:

    【解决方案3】:

    这个 LINQ 查询可能会帮助您找到带索引的格式化名称:

    var accidents=(from acc in accidents
        select new {
            id=accidents.IndexOf(acc),
            Name = acc.Replace("\"", string.Empty)
        }).ToArray()
    

    或者,如果您希望结果为 IEnumerable 格式,也可以使用 .ToList()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-26
      • 2023-04-09
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2014-06-04
      相关资源
      最近更新 更多