Smart enumerations

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…

Visual Studio 2008 (Orcas) Beta 2 Released

Somehow I’d managed to miss this announcement, as had some other people on the C# newsgroup, so I thought it would be worth posting here too. Visual Studio 2008 (Orcas) beta 2 has been released, and it’s now feature complete, apparently. Finally I get to use automatic properties! This time I’m going to take the risk of installing it onto my home laptop “properly” as opposed to using a Virtual PC – after backing up, of course.

I’ve been downloading via the MSDN subscriptions file transfer manager, and have been getting a great transfer rate – better than the download sites listed below, so if you’re an MSDN subscriber, I’d try that way first.

Related links: