IEnumerable.使用索引选择
本文关键字:选择 索引 IEnumerable | 更新日期: 2023-09-27 18:32:58
我有以下代码:
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,还是必须老派?
我不确定您要查找哪种索引,但如果它只是一组连续的数字,那么您很幸运。Select
重载正是这样做的:
return accidents.Select((t, i) => new Accident() {Id = i, Name = t.Replace("'"", string.Empty)}).ToArray();
它需要一个采用两个参数的委托 - 项及其索引。
使用
Enumerable.Range 生成 ID 值,然后使用当前值索引到字符串数组中:
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()
。