使用IEnumerable.Select和索引

12

I have the following code:

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

这里 accidents 是一个字符串数组。

我想要将字符串数组通过 Linq 转换为 Accident 对象数组,如下所示:

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

我该如何使用Linq从事故数组中检索索引i,还是必须老派地去做?

2
你想要从accidents数组本身获取索引,还是从原始的text枚举中获取索引?如果是前者,那么Marcin的答案就可以了。如果是后者,那么你需要在最初引入索引的Select()之后进行Skip()Take()操作。 - Peter Duniho
3个回答

24

我不确定您需要哪种类型的索引,但如果只是一组连续的数字,那么您很幸运。有一个Select重载函数可以实现这个功能:

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

它需要一个委托,该委托接收两个参数 - 项和其索引。

我只需要一组连续的数字,谢谢。 - Klaus Nji

2
使用Enumerable.Range生成ID值,然后使用当前值索引String数组:
Enumerable.Range(0, accidents.Length).Select(f => new Accident() { Id = f, Name = accidents[f] })

0

也许这个LINQ查询可以帮助你找到带索引的格式化名称:

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

或者你也可以使用.ToList(),如果你想要结果以IEnumerable格式返回。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接