.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}");
}
相关推荐
武藤一雄2 天前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
csdn_aspnet4 天前
在 ASP.NET Core 中使用自定义属性实现 HTTP 请求和响应加密
http·asp.net·.netcore
观无4 天前
.NET Core + Ocelot 网关 跨域 (CORS) 配置
状态模式·.netcore
csdn_aspnet4 天前
如何在 .NET Core WebAPI 和 Javascript 应用程序中安全地发送/接收密钥参数
javascript·.netcore·cryptojs
武藤一雄6 天前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
武藤一雄7 天前
C#万字详解 栈与托管堆 的底层逻辑
windows·microsoft·c#·.net·.netcore
武藤一雄7 天前
深入拆解.NET内存管理:从GC机制到高性能内存优化
windows·microsoft·c#·.net·wpf·.netcore·内存管理
武藤一雄9 天前
WPF/C# 应对消息洪峰与数据抖动的 8 种“抗压”策略
windows·微软·c#·wpf·.netcore·防抖·鲁棒性
武藤一雄10 天前
C# 竟态条件
microsoft·c#·.net·.netcore
武藤一雄10 天前
WPF深度解析Behavior
windows·c#·.net·wpf·.netcore