.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}");
}
相关推荐
dephixf20 小时前
工业级部署指南:在西门子IOT2050(Debian 12)上搭建.NET 9.0环境与应用部署
物联网·.netcore·智能制造·边缘网关·西门子·iot 2050
睡前要喝豆奶粉21 小时前
在.NET Core Web Api中使用JWT并配置UserContext获取用户信息
前端·.netcore
睡前要喝豆奶粉21 小时前
在.NET Core Web Api中使用阿里云OSS
阿里云·c#·.netcore
周杰伦fans1 天前
.NET Core WebAPI 中 HTTP 请求方法详解:从新手到精通
网络协议·http·.netcore
睡前要喝豆奶粉3 天前
.NET Core Web API开发需引入的三个基本依赖配置说明
oracle·c#·.netcore
睡前要喝豆奶粉3 天前
.NET Core Web API中数据库相关配置
数据库·c#·.netcore
Archy_Wang_14 天前
Hangfire 入门与实战:在 .NET Core 中实现可靠后台任务处理
c#·.netcore
睡前要喝豆奶粉4 天前
在.NET Core Web Api中使用redis
redis·c#·.netcore
睡前要喝豆奶粉5 天前
多表分页联查——EF Core方式和Dapper方式
c#·.netcore
csdn_aspnet6 天前
.NETCore、.NET 7 和 RabbitMQ 的发布-订阅模式
rabbitmq·.netcore·.net7.