Other ways to deal with “loop initialization” in C#

前端 未结 9 763
陌清茗
陌清茗 2020-12-24 07:22

To start with I\'ll say that I agree that goto statements are largely made irrelevant by higher level constructs in modern programming languages and shouldn\'t be used when

9条回答
  •  离开以前
    2020-12-24 07:52

    Personally I like Mark Byer's option, but you could always write your own generic method for this:

    public static void IterateWithSpecialFirst(this IEnumerable source,
        Action firstAction,
        Action subsequentActions)
    {
        using (IEnumerator iterator = source.GetEnumerator())
        {
            if (iterator.MoveNext())
            {
                firstAction(iterator.Current);
            }
            while (iterator.MoveNext())
            {
                subsequentActions(iterator.Current);
            }
        }
    }
    

    That's relatively straightforward... giving a special last action is slightly harder:

    public static void IterateWithSpecialLast(this IEnumerable source,
        Action allButLastAction,
        Action lastAction)
    {
        using (IEnumerator iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                return;
            }            
            T previous = iterator.Current;
            while (iterator.MoveNext())
            {
                allButLastAction(previous);
                previous = iterator.Current;
            }
            lastAction(previous);
        }
    }
    

    EDIT: As your comment was concerned with the performance of this, I'll reiterate my comment in this answer: while this general problem is reasonably common, it's not common for it to be such a performance bottleneck that it's worth micro-optimizing around. Indeed, I can't remember ever coming across a situation where the looping machinery became a bottleneck. I'm sure it happens, but that isn't "common". If I ever run into it, I'll special-case that particular code, and the best solution will depend on exactly what the code needs to do.

    In general, however, I value readability and reusability much more than micro-optimization.

提交回复
热议问题