.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}");
}
相关推荐
van久1 天前
Day15:EF Core 入门 + CodeFirst(就业核心版)
.netcore
叫我黎大侠1 天前
.NET 实战:调用千问视觉模型实现 OCR(车票识别完整教程)
阿里云·ai·c#·ocr·asp.net·.net·.netcore
van久1 天前
Day15-4:【日志】中间件和过滤器 的对比选择
.netcore
van久2 天前
Day14: 搭建企业标准的DDD 简洁版四层架构
架构·.netcore
van久2 天前
ADay15-1: 安装 EF Core 包 到 对应DDD(领域驱动设计)四层架构‌
.netcore
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 69 期(2026年4.01-4.12)
c#·.net·.netcore
willhuo5 天前
基于Playwright的抖音网页自动化浏览器项目使用指南
爬虫·c#·.netcore·webview
csdn_aspnet6 天前
在 .NET Core 8 中实现 CORS
.netcore·跨域·cors·.net8
csdn_aspnet7 天前
在 ASP.NET Core (WebAPI) 中启用 CORS
后端·asp.net·.netcore
观无8 天前
Windows 本地电脑搭建一个私有的、类似 Gitee 的 Git 服务
gitee·jenkins·.netcore