.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}");
}
相关推荐
小先生8126 天前
.NET Core后台任务队列
.net·.netcore
MoFe16 天前
【.net core】【watercloud】动态数据转换为静态表格,或者表格数据返回需要后处理
.netcore
吹牛不交税12 天前
.netcore项目部署在ubuntu22.04虚拟机的docker中的过程记录
docker·容器·.netcore
weixin_4219947815 天前
基于 .NET 9.0 的高性能轻量级令牌桶限流服务
.net·.netcore·令牌桶
weixin_4219947816 天前
MVC 模式初探
mvc·.net·.netcore
weixin_4219947817 天前
互联网与 Web 应用简介
.net·.netcore
全栈小519 天前
【C#】合理使用DeepSeek相关AI应用为我们提供强有力的开发工具,在.net core 6.0框架下使用JsonNode动态解析json字符串,如何正确使用单问号和双问号做好空值处理
人工智能·c#·json·.netcore·deepseek
时光追逐者20 天前
C#/.NET/.NET Core优秀项目和框架2026年1月简报
c#·.net·.netcore
大尚来也23 天前
双库协同,各取所长:.NET Core 中 PostgreSQL 与 SQLite 的优雅融合实战
postgresql·sqlite·.netcore
吹牛不交税23 天前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore