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

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

    You can refactor your code well enough so that you won't see them often. A good function name is definitely more readable that a for loop.

    Taking the example from AndyC :

    Loop

    // mystrings is a string array
    List myList = new List();
    foreach(string s in mystrings)
    {
        if(s.Length > 5)
        {
            myList.add(s);
        }
    }
    

    Linq

    // mystrings is a string array
    List myList = mystrings.Where(t => t.Length > 5)
                                   .ToList

    Wheter you use the first or the second version inside your function, It's easier to read

    var filteredList = myList.GetStringLongerThan(5);
    

    Now that's an overly simple example, but you get my point.

提交回复
热议问题