IEnumerable.Select with index

Kla*_*Nji 9 c# linq ienumerable

我有以下代码:

 var accidents = text.Skip(NumberOfAccidentsLine + 1).Take(numberOfAccidentsInFile).ToArray();
Run Code Online (Sandbox Code Playgroud)

事故是一系列的字符串.

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

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

如何使用Linq从事故阵列中检索索引i还是我必须上学?

Mar*_*zek 17

我不确定你正在寻找什么样的指数,但如果它只是一组连续的数字那么你很幸运.有Select重载正是这样:

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

它需要一个带有两个参数的委托 - 项目及其索引.