.NET Core 3 foreach中取索引index

for和foreach 循环是 C# 开发人员工具箱中最有用的构造之一。

在我看来,迭代一个集合比大多数情况下更方便。

它适用于所有集合类型,包括不可索引的集合类型(如 ,并且不需要通过索引访问当前元素)。

但有时,确实需要当前项的索引;这通常会使用以下模式之一:

// 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:只需编写这样的扩展方法:

public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
    return source.Select((item, index) => (item, index));
}

调用方法:

foreach (var (item, index) in collection.WithIndex())
{
    DoSomething(item, index);
}

注意:集合后面的WithIndex();

如果闲扩展方法比较麻烦,也可以使用解决方案二:

foreach (var (item, index) in list.Select((value, i) => (value, i)))
{
    Console.WriteLine($"{index},{item}");
}

相关推荐

  1. .NET Core 3 foreach索引index

    2024-02-07 07:46:05       48 阅读
  2. 006_logical_index_in_Matlab的逻辑数组索引

    2024-02-07 07:46:05       37 阅读
  3. MySQL为什么要使用索引合并(Index Merge)

    2024-02-07 07:46:05       26 阅读
  4. mybatisforeach使用

    2024-02-07 07:46:05       37 阅读
  5. MySQL 索引 create index 详解

    2024-02-07 07:46:05       65 阅读
  6. SQLite索引名称重复(index already exists)

    2024-02-07 07:46:05       27 阅读
  7. Oracle(15)什么是索引Index)?

    2024-02-07 07:46:05       17 阅读
  8. 详细分析Mybatis的<foreach>标签

    2024-02-07 07:46:05       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-07 07:46:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-07 07:46:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-07 07:46:05       87 阅读
  4. Python语言-面向对象

    2024-02-07 07:46:05       96 阅读

热门阅读

  1. spring boot学习第十一篇:发邮件

    2024-02-07 07:46:05       46 阅读
  2. 2.6学习总结10

    2024-02-07 07:46:05       51 阅读
  3. 算法——C/动态规划

    2024-02-07 07:46:05       52 阅读
  4. openssl3.2 - update debian12‘s default openssl to openssl3.2

    2024-02-07 07:46:05       53 阅读
  5. Golang context 万字解析实现原理

    2024-02-07 07:46:05       46 阅读
  6. Qt::invokeMethod

    2024-02-07 07:46:05       55 阅读
  7. python的not

    2024-02-07 07:46:05       54 阅读
  8. sensor_msgs::PointCloud2 与sensor_msgs::PointCloud的区别

    2024-02-07 07:46:05       52 阅读
  9. 作业2.6

    作业2.6

    2024-02-07 07:46:05      42 阅读