IEnumerable.Select with index

我有以下代码:

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从事故arrays中检索索引i还是我必须上学?

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

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

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

使用Enumerable.Range生成ID值,然后使用当前值索引到String Array:

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

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

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

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