带索引的 foreach [英] foreach with index

查看:21
本文介绍了带索引的 foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 C# 等效于 Python 的 enumerate() 和 Ruby 的 each_with_index?

Is there a C# equivalent of Python's enumerate() and Ruby's each_with_index?

推荐答案

我保留了这个扩展方法:

I keep this extension method around for this:

public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
{
    var i = 0;
    foreach (var e in ie) action(e, i++);
}

并像这样使用它:

var strings = new List<string>();
strings.Each((str, n) =>
{
    // hooray
});

或者允许类似 break 的行为:

Or to allow for break-like behaviour:

public static bool Each<T>(this IEnumerable<T> ie, Func<T, int, bool> action)
{
    int i = 0;
    foreach (T e in ie) if (!action(e, i++)) return false;
    return true;
}

var strings = new List<string>() { "a", "b", "c" };

bool iteratedAll = strings.Each ((str, n)) =>
{
    if (str == "b") return false;
    return true;
});

这篇关于带索引的 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆