I have an IEnumerable
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.