Say you want to loop through 3 elements like this:
for(int i=0; i<3; i++)
{
doSomething();
}
Of course, this is the same as saying: doSomething(); doSomething(); doSomething();
.
Now, let's say you want to do something BETWEEN each iteration, as if you are coding this:
doSomething(); doBetween(); doSomething(); doBetween(); doSomething();
Notice how doSomething()
is called 3 times, but doBetween()
is called 2 times.
Right now, the only way I know how to do this in a loop is:
for(int i=0; i<3; i++)
{
doSomething();
if(i<2)
doBetween();
}
To me, it seems inefficient to run that conditional within a loop. It also makes you have to look at it twice in order to understand the programming intention. Plus, if you change the "3" to something else in the "for" header, you could easily forget to change the conditional, especially as the logic grows. Not only that, but this trick won't work in a foreach loop because there is no easy way to detect whether we are running the last iteration.
What tips do you have for doing something like this in a way that gives you better performance, better readability, better maintainability, or in a foreach loop?
You could always write a reusable function, not sure this would be a good idea unless you needed to reuse this a lot
public static IEnumerable<TSource> ForEach<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Action<TSource> action, Action<TSource> between)
{
bool first = true;
foreach (TSource item in source)
{
if (first) first = false; else between();
action(item);
}
return source;
}
This would be called like so:
myList.ForEach(i => DoSomething(), i => DoBetween());
Or
Enumerable.Range(0, 3).ForEach(i => DoSomething(), i => DoBetween());