I have a function running over an enumerable, but the function should be a little bit different for the first item, for example:
void start() {
List<string> a = ...
a.ForEach(DoWork);
}
bool isFirst = true;
private void DoWork(string s) {
// do something
if(isFirst)
isFirst = false;
else
print("first stuff");
// do something
}
How would you refactor this to avoid that ugly flag?
EDIT: added usage example, added a ForFirst method, reordered my paragraphs.
Below is a complete solution.
Usage is either of the following:
The crux is the
ForNextmethod, which performs an action for the specified next set of items from the collection and returns the remaining items. I’ve also implemented aForFirstmethod that simply calls ForNext with count: 1.I felt a bit ridiculous making the
ForRemaindermethod; I could swear that I was re-implementing a built-in function with that, but it wasn’t coming to mind and I couldn’t find an equivalent after glancing around a bit. UPDATE: After reading the other answers, I see there apparently isn’t an equivalent built into Linq. I don’t feel so bad now.