This afternoon, my team leader checked with me that there really was no way of telling when the current iteration of a foreach
loop is the last one. I confirmed the situation, and immediately thought, “Well, why isn’t there a way?” I know that you can’t tell without peeking ahead, but surely there’s a simple way of doing that in a general purpose fashion…
About 15 minutes later, SmartEnumerable<T>
was born, or at least something with the same functionality. It chains whatever enumeration you give it (in the same way as a lot of the LINQ calls do) but adds extra information about whether this is the first and/or last element in the enumeration, and the notional index of the element. An example will probably make this clearer. Here’s some example code:
using System; using System.Collections.Generic; using MiscUtil.Collections; class Example { static void Main(string[] args) { List<string> list = new List<string>(); list.Add("a"); list.Add("b"); list.Add("c"); list.Add("d"); list.Add("e"); foreach (SmartEnumerable<string>.Entry entry in new SmartEnumerable<string>(list)) { Console.WriteLine ("{0,-7} {1} ({2}) {3}", entry.IsLast ? "Last ->" : "", entry.Value, entry.Index, entry.IsFirst ? "<- First" : ""); } } } |
The output is as follows:
a (0) <- First b (1) c (2) d (3) Last -> e (4) |
I’m pretty pleased with that – but annoyed with myself for not thinking of doing it before. I’m pretty shocked that I haven’t seen it elsewhere; the code behind it is really straightforward. Anyway, it’s now part of my Miscellaneous Utilities library, so feel free to have at it.
Of course, if any of you cunning readers have seen the same thing elsewhere, feel free to indicate just how ignorant I am…