Neat way to write loop that has special logic for the first item in a collection

后端 未结 12 2615
忘了有多久
忘了有多久 2021-02-13 17:31

Often I have to code a loop that needs a special case for the first item, the code never seems as clear as it should ideally be.

Short of a redesign of the C# language,

12条回答
  •  梦如初夏
    2021-02-13 17:56

    IMHO the most cleanest way is: try to avoid special cases for the first item. That may not work in every situation, of course, but "special cases" may indicate that your program logic is more complex than it needs to be.

    By the way, I would not code

    if (yyy.Length > 0)
    {
       for(int i = 1; i 

    but instead

       for(int i = 1; i 

    (which is itself a simple example of how to avoid unnecessary dealing with a special case.)

提交回复
热议问题