.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}");
}
相关推荐
deriva2 天前
.netcore+ef+redis+rabbitmq+dotcap先同步后异步再同步的方法,亲测有效
redis·rabbitmq·.netcore
棉晗榜18 天前
C# .net core添加单元测试项目,依赖注入接口测试
单元测试·c#·.netcore
时光追逐者18 天前
.NET初级软件工程师面试经验分享
经验分享·面试·职场和发展·c#·.net·.netcore
忧郁的蛋~19 天前
.NET Core 实现缓存的预热的方式
缓存·c#·.net·.netcore
csdn_aspnet20 天前
C# .NET Core 源代码生成器(dotnet source generators)
c#·.netcore
时光追逐者20 天前
C#/.NET/.NET Core技术前沿周刊 | 第 42 期(2025年6.9-6.15)
c#·.net·.netcore
csdn_aspnet21 天前
使用 C# 源生成器(Source Generators)进行高效开发:增强 Blazor 及其他功能
c#·.netcore
lgaof65822@gmail.com23 天前
Asp.Net Core SignalR导入数据
前端·后端·asp.net·.netcore
眸笑丶23 天前
.NET Core 数据库连接字符串加密与解密
数据库·oracle·.netcore
时光追逐者1 个月前
C#/.NET/.NET Core技术前沿周刊 | 第 41 期(2025年6.1-6.8)
c#·.net·.netcore