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

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

    Both of those are perfectly acceptable algorithms for processing the first element differently, and there really isn't a different way to do it. If this pattern is repeated a lot, you could hide it behind an overload of ForEach():

    public static void ForEach(this IEnumerable elements, Action firstElementAction, Action standardAction)
    {
        var firstItem = true;
        foreach(T element in elements)
        {
            if(firstItem)
            {
                firstItem = false;
                firstElementAction(element)
            }
            else
                standardAction(element)
        }
    }
    
    ...
    
    //usage
    yyy.ForEach(t=>(other code when first item), t=>(normal processing code));
    

    Linq makes it a little cleaner:

    PerformActionOnFirstElement(yyy.FirstOrDefault());
    yyy.Skip(1).ForEach(x=>(normal processing code));
    

提交回复
热议问题