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

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

    I use the first variable method all the time and it seems totally normal to me. If you like that better you can use LINQ First() and Skip(1)

    var firstItem = yyy.First();
    // do the whatever on first item
    
    foreach (var y in yyy.Skip(1))
    {
    // process the rest of the collection
    }
    

提交回复
热议问题