.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}");
}
相关推荐
时光追逐者14 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
切糕师学AI20 小时前
.net core web程序如何设置redis预热?
redis·.netcore
csdn_aspnet2 天前
ASP.NET Core 中的多租户 SaaS 应用程序
.netcore·saas
时光追逐者7 天前
C#/.NET/.NET Core技术前沿周刊 | 第 49 期(2025年8.1-8.10)
c#·.net·.netcore
切糕师学AI7 天前
在 .NET Core 5.0 中启用 Gzip 压缩 Response
.netcore
周杰伦fans9 天前
.NET Core MVC中CSHTML
mvc·.netcore
爱吃香蕉的阿豪15 天前
乐思 AI 智能识别平台(基于 YOLO,.NET+Vue3 开发)开源指南
人工智能·yolo·开源·aigc·.netcore
时光追逐者16 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
步、步、为营21 天前
.NET Core 3.1 升级到 .NET 8
microsoft·.net·.netcore
时光追逐者23 天前
C#/.NET/.NET Core技术前沿周刊 | 第 48 期(2025年7.21-7.27)
c#·.net·.netcore·.net core