.NET Core 3 foreach中取索引index

for和foreach 循环是 C# 开发人员工具箱中最有用的构造之一。

在我看来,迭代一个集合比大多数情况下更方便。

它适用于所有集合类型,包括不可索引的集合类型(如 ,并且不需要通过索引访问当前元素)。

但有时,确实需要当前项的索引;这通常会使用以下模式之一:

cs 复制代码
// foreach 中叠加 index 变量值
int index = 0;
foreach (var item in collection)
{
    DoSomething(item, index);
    index++;
}

// 普通的 for 循环
for (int index = 0; index < collection.Count; index++)
{
    var item = collection[index];
    DoSomething(item, index);
}

**解决方案1:**只需编写这样的扩展方法:

cs 复制代码
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
    return source.Select((item, index) => (item, index));
}

调用方法:

cs 复制代码
foreach (var (item, index) in collection.WithIndex())
{
    DoSomething(item, index);
}

注意:集合后面的WithIndex();

如果闲扩展方法比较麻烦,也可以使用解决方案二:

cs 复制代码
foreach (var (item, index) in list.Select((value, i) => (value, i)))
{
    Console.WriteLine($"{index},{item}");
}
相关推荐
[email protected]13 小时前
ASP.NET Core SignalR - 部分客户端消息发送
后端·asp.net·.netcore
bbsh209913 小时前
WebFuture:Ubuntu 系统上在线安装.NET Core 8 的步骤
linux·ubuntu·.netcore·webfuture
MoFe11 天前
【.net core】【watercloud】树形组件combotree导入及调用
.netcore
MoFe11 天前
【.net core】.KMZ文件解压为.KML文件并解析为GEOJSON坐标数据集。附KML处理多线(LineString)闭环问题
.netcore
The Future is mine2 天前
在.NET Core控制器中获取AJAX传递的Body参数
c#·.netcore
无味无感2 天前
ASP.NET Core使用Quartz部署到IIS资源自动被回收解决方案
.netcore
MoFe12 天前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
步、步、为营3 天前
.NET Core接口IServiceProvider
.net·.netcore
冰茶_5 天前
建造者模式:优雅构建复杂对象
设计模式·微软·c#·.netcore·建造者模式·软件开发
冰茶_5 天前
结构型设计模式之桥接模式
学习·设计模式·微软·c#·.netcore·桥接模式