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

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

    Here's a slightly simpler extension method that does the job. This is a combination of KeithS's solution and my answer to a related Java question:

    public static void ForEach(this IEnumerable elements,
                                  Action firstElementAction,
                                  Action standardAction)
    {
        var currentAction = firstElementAction;
        foreach(T element in elements)
        {
            currentAction(element);
            currentAction = standardAction;
        }
    }
    

提交回复
热议问题