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

后端 未结 12 2646
忘了有多久
忘了有多久 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:39

    Another option I came up with is

    enum ItemType
    {
      First,
      Last,
      Normal
    }
    
    list.Foreach(T item, ItemType itemType) =>
    {
       if (itemType == ItemType.First)
       {
       }
    
       // rest of code
    };
    

    Writing the extension method is left as an exercise for the reader… Also should two Boolean flags “IsFirst” and “IsLast” be used instead of ItemType enum, or ItemType be an object that has “IsFirst” and “IsLast” properties?

提交回复
热议问题