.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}");
}
相关推荐
勿芮介18 小时前
[开发技术]在.NetCore中使用Elsa工作流-初学篇
.netcore
我是苏苏18 小时前
已解决:.NetCore控制台程序(WebAPI)闪退,没有报错日志定位不到信息
.netcore
时光追逐者19 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 62 期(2025年11.17-11.23)
c#·.net·.netcore
宝桥南山1 天前
.NET 10 - Blazor web assembly应用的一些诊断方式
microsoft·微软·c#·asp.net·.net·.netcore
FuckPatience1 天前
.netcoreapp2.0与.Net Core是什么关系
c#·.net·.netcore
周杰伦fans5 天前
CommunityToolkit.Mvvm(又称MVVM Toolkit) 与 MvvmLight 的核心区别
开发语言·c#·.netcore
时光追逐者8 天前
C#/.NET/.NET Core技术前沿周刊 | 第 61 期(2025年11.10-11.16)
c#·.net·.netcore
夏霞12 天前
c# ASP.NET Core SignalR 客户端配置自动重连次数
c#·.netcore
BXS_null12 天前
windows、linux/ubuntu 系统运用.net core使用Selenium WebDriver实现自动化测试
linux·ubuntu·.netcore