• Last night I was hacking out a lambda to generate an Excel column label.

    I got to this – it looks a bit messy to me – can anyone come up with an improvement?

    Essentially the use case is to generate these strings, in order: A,B,C…Z,AA,AB,AC…AZ,BA,BB,BC…BZ,…,ZA..ZZ, AAA, AAB, AAC…ad infinitum.



     var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

     var i = new List(){0};

     Func<String> getNextColumn = () =>

     {

       var sb = new StringBuilder();

       var addOne = false;

       var incIndex = -1;

       for (var j = 0; j < i.Count; j++)

       {

        var n = i[j];

        sb.Append(letters[n]);

        if (j == i.Count - 1)

        {

         n = n + 1;

        }

        if (n > letters.Length - 1)

        {

         n = 0;

         if (j == 0)

         {

          addOne = true;

         }

         else if (letters[i[j - 1]] == 'Z')

         {

          addOne = true;

         }

         else

         {

          incIndex = j - 1;

         }

        }

        i[j] = n;

       }

       if (addOne) { i.Add(0); }

       if (incIndex >= 0) { i[incIndex] += 1; }

       return sb.ToString();

     };



    This lambda is defined within a function that generates cells (rows are easy, cos they are just sequential numbers). The function itself is then creating a sheet and calling off ‘getNextColumn’ when it needs to.

    • Hacking last night - Media Science

      Last night I was hacking out a lambda to generate an Excel column label. I got to this - it looks a bit messy to me - can anyone come up with an improvement? Essentially the use case is to generate these strings, in order: A,B,C...Z,AA,AB,AC...AZ,BA,BB,BC...BZ,...,ZA..ZZ, AAA, AAB, AAC...ad infinitum.