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

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

    1. For loops are not bad. There are many very valid reasons to keep a for loop.
    2. You can often "avoid" a for loop by reworking it using LINQ in C#, which provides a more declarative syntax. This can be good or bad depending on the situation:

    Compare the following:

    var collection = GetMyCollection();
    for(int i=0;i

    vs foreach:

    var collection = GetMyCollection();
    foreach(var item in collection)
    {
         if(item.MyValue == someValue)
              return item;
    }
    

    vs. LINQ:

    var collection = GetMyCollection();
    return collection.FirstOrDefault(item => item.MyValue == someValue);
    

    Personally, all three options have their place, and I use them all. It's a matter of using the most appropriate option for your scenario.

提交回复
热议问题