如何创建For_Each_With_Condition_With_Index扩展方法(EM)

时间:2012-05-16 07:09:18

标签: c# extension-methods

我有ForEachWithIndex EM

static void ForEachWithIndex<T>(this IEnumerable<T> enu, Action<T, int> action)
{
    int i = 0;
    foreach(T item in enu)
        action(item, i++);
}

我称之为

my_int_array.ForEachWithIndex((x, i) => x += i);

现在我想创建一个检查条件,然后执行该操作。

通常我在上面使用

my_int_array.ForEachWithIndex((x,i) => 
{
    if (x != 0)
        x += i;
});

我想要一个将该条件作为参数的EM。怎么做?

3 个答案:

答案 0 :(得分:3)

我会尽量避免构建一个可以完成所有操作的大扩展方法。打破它,就像LINQ一样。

我个人实际上不会做任何 - 我会用LINQ构建一个查询,然后使用foreach语句来执行操作:

// Assuming you want the *original* indexes
var query = array.Select((Value, Index) => new { value, Index })
                 .Where(pair => pair.Index != 0);

foreach (var pair in query)
{
    // Do something
}

很难确切知道你要做什么,因为增加lambda参数并不能真正实现任何目标。我强烈建议您考虑编写块...而且您可能会发现Eric Lippert's views on foreach vs ForEach很有趣。

答案 1 :(得分:1)

只需将条件委托添加到参数列表:

static void ForEachWithIndexWithCondition<T>(this IEnumerable<T> enu, 
                     Func<T, int, bool> condition, Action<T, int> action)
{
    int i = 0;
    foreach (T item in enu)
    {
        if (condition(item, i))
            action(item, i);
        i++;
     }
}

用法:

        var list = new List<string> { "Jonh", "Mary", "Alice", "Peter" };

        list.ForEachWithIndexWithCondition(
            (s, i) => i % 2 == 0,
            (s, i) => Console.WriteLine(s));

答案 2 :(得分:0)

您需要传递一个额外的Func参数,如下所示:

public static void ForEachWithIndex<T>(this IEnumerable<T> enu,
                           Action<T, int> action, Func<T, int, bool> condition)
{
    int i = 0;
    foreach (T item in enu)
    {
        if (condition(item, i))
        {
            action(item, i);
        }
        ++i;
    }
}

这就是你的例子的代码:

my_int_array.ForEachWithIndex((x, i) => x += i, (x, i) => x != 0);
相关问题