How to replace for-loops with a functional statement in C#?

前端 未结 18 1783
不思量自难忘°
不思量自难忘° 2021-01-31 08:59

A colleague once said that God is killing a kitten every time I write a for-loop.

When asked how to avoid for-loops, his answer was to use a functional language. However

18条回答
  •  面向向阳花
    2021-01-31 09:27

    Your colleague is wrong about for loops being bad in all cases, but correct that they can be rewritten functionally.

    Say you have an extension method that looks like this:

    void ForEach(this IEnumerable collection, Action  action)
    {
        foreach(T item in collection)
        {
            action(item)
        }
    }
    

    Then you can write a loop like this:

    mycollection.ForEach(x => x.DoStuff());
    

    This may not be very useful now. But if you then replace your implementation of the ForEach extension method for use a multi threaded approach then you gain the advantages of parallelism.

    This obviously isn't always going to work, this implementation only works if the loop iterations are completely independent of each other, but it can be useful.

    Also: always be wary of people who say some programming construct is always wrong.

提交回复
热议问题