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

后端 未结 12 2874
忘了有多久
忘了有多久 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 18:01

    How about:

    using (var erator = enumerable.GetEnumerator())
    {
        if (erator.MoveNext())
        {
            ProcessFirst(erator.Current);
            //ProcessOther(erator.Current); // Include if appropriate.
    
            while (erator.MoveNext())
                ProcessOther(erator.Current);
        }
    }
    

    You could turn that into an extension if you want:

    public static void Do(this IEnumerable source, 
                             Action firstItemAction,
                             Action otherItemAction)
    {
       // null-checks omitted
    
        using (var erator = source.GetEnumerator())
        {
            if (!erator.MoveNext())
                return;
    
            firstItemAction(erator.Current);
    
            while (erator.MoveNext())
               otherItemAction(erator.Current);            
        }
    }
    

提交回复
热议问题