.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}");
}
相关推荐
csdn_aspnet2 天前
MongoDB C# .NetCore 驱动程序 序列化忽略属性
mongodb·c#·.netcore
Tiger_shl3 天前
【.Net技术栈梳理】08-控制反转(IoC)与依赖注入(DI)
开发语言·.net·.netcore
Tiger_shl3 天前
【.Net技术栈梳理】10-.NET Core 程序的执行
开发语言·.net·.netcore
MoFe13 天前
【.net core】【watercloud】登陆后跳转至指定页面,显示在系统框架页内
.netcore
周杰伦fans3 天前
.net core webapi/mvc阿里云服务器部署 - 错误解决
阿里云·mvc·.netcore
驾驭人生6 天前
Asp .Net Core 系列:Asp .Net Core 集成 Hangfire+MySQL
数据库·mysql·.netcore
时光追逐者6 天前
C#/.NET/.NET Core技术前沿周刊 | 第 53 期(2025年9.1-9.7)
c#·.net·.netcore
somethingGoWay7 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay7 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
切糕师学AI8 天前
如何建立针对 .NET Core web 程序的线程池的长期监控
java·前端·.netcore