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

前端 未结 18 2138
不思量自难忘°
不思量自难忘° 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:18

    Functional constructs often express your intent more clearly than for-loops in cases where you operate on some data set and want to transform, filter or aggregate the elements.

    Loops are very appropriate when you want to repeatedly execute some action.


    For example

    int x = array.Sum();
    

    much more clearly expresses your intent than

    int x = 0;
    for (int i = 0; i < array.Length; i++)
    {
        x += array[i];
    }
    

提交回复
热议问题