IEnumerable foreach, do something different for the last element

后端 未结 5 2294
庸人自扰
庸人自扰 2021-02-20 06:23

I have an IEnumerable. I want to do one thing for each item of the collection, except the last item, to which I want to do something else. How can I code this neatly? I

5条回答
  •  鱼传尺愫
    2021-02-20 06:45

    If you want to do this as efficiently as possible there is no other choice than effectively looking at not only the current but also the "next" or "previous" item, so you can defer the decision of what to do after you have that information. For example, assuming T is the type of items in the collection:

    if (collection.Any()) {
        var seenFirst = false;
        T prev = default(T);
        foreach (var current in collection) {
            if (seenFirst) Foo(prev);
            seenFirst = true;
            prev = current;
        }
        Bar(prev);
    }
    

    See it in action.

提交回复
热议问题