.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}");
}
相关推荐
1-1=013 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
1-1=016 天前
C# IO和序列化
c#·.net·.netcore
宝桥南山17 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=018 天前
C# 特性(Attribute)
c#·.net·.netcore
淡海水19 天前
10-01-互操作-C#与C++边界的内存管理
unity·c#·游戏引擎·.netcore·gc
1-1=019 天前
C# 反射
c#·.net·.netcore
1-1=020 天前
C# 泛型
c#·.net·.netcore
淡海水22 天前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
1-1=022 天前
.NET Core 编译技术
.net·.netcore
1-1=023 天前
.NET Core 文件系统
.net·.netcore·1024程序员节