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

后端 未结 12 2645
忘了有多久
忘了有多久 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条回答
  •  猫巷女王i
    2021-02-13 17:35

    I'd be tempted to use a bit of linq

    using System.Linq;
    
    var theCollectionImWorkingOn = ...
    
    var firstItem = theCollectionImWorkingOn.First();
    firstItem.DoSomeWork();
    
    foreach(var item in theCollectionImWorkingOn.Skip(1))
    {
        item.DoSomeOtherWork();
    }
    

提交回复
热议问题