📜  IEnumerable ForEach - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:45.405000             🧑  作者: Mango

代码示例1
public static class Enumerables
{
    public static void ForEach(this IEnumerable @this, Action action)
    {
        foreach (T item in @this)
        {
            action(item);
        }
    }
}

class Program
{
    private static void NoOp(int value) {}

    static void Main(string[] args)
    {
        var list = Enumerable.Range(0, 10).ToList();
        for (int i = 0; i < 1000000; i++)
        {
            // WithLinq(list);
            // WithoutLinqNoGood(list);
            WithoutLinq(list);
        }
    }

    private static void WithoutLinq(List list)
    {
        foreach (var item in list)
        {
            NoOp(item);
        }
    }

    private static void WithLinq(IEnumerable list) => list.ForEach(NoOp);

    private static void WithoutLinqNoGood(IEnumerable enumerable)
    {
        foreach (var item in enumerable)
        {
            NoOp(item);
        }
    }
}