管理杂谈OA答疑ERP答疑教程搜索

C#在foreach中巧取索引(index)


引子

forforeach 循环是 C# 开发人员工具箱中最有用的构造之一。
在我看来,迭代一个集合比大多数情况下更方便。
它适用于所有集合类型,包括不可索引的集合类型(如 ,并且不需要通过索引访问当前元素)。
但有时,确实需要当前项的索引;前段时间开发中用foreach遍历集合就遇到这个问题。这通常会使用以下模式之一:
// 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);}

它一直让我恼火;难道我们不能同时得到值和索引吗?

原来有个简单的解决方案,用 Linq 和 元组。

解决方案1:

只需编写这样的扩展方法:

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

以上代码请引入以下命名空间:

using System.Linq;

调用方法

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

注意:集合后面的WithIndex()

解决方案2:

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

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

大功告成,对性能有一点影响,大家可以观察按需使用!!


更多精彩文章浏览...
点击右上角图标分享到朋友圈
官方网站:http://www.clicksun.cn
咨询热线:400-186-1886
服务邮箱:service@clicksun.cn