Fastest function to generate Excel column letters in C#

前端 未结 21 1786
无人共我
无人共我 2020-11-29 02:30

What is the fastest c# function that takes and int and returns a string containing a letter or letters for use in an Excel function? For example, 1 returns \"A\", 26 return

21条回答
  •  没有蜡笔的小新
    2020-11-29 03:04

    Here is a concise implementation using LINQ.

    static IEnumerable GetExcelStrings()
    {
        string[] alphabet = { string.Empty, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
    
        return from c1 in alphabet
               from c2 in alphabet
               from c3 in alphabet.Skip(1)                    // c3 is never empty
               where c1 == string.Empty || c2 != string.Empty // only allow c2 to be empty if c1 is also empty
               select c1 + c2 + c3;
    }
    

    This generates A to Z, then AA to ZZ, then AAA to ZZZ.

    On my PC, calling GetExcelStrings().ToArray() takes about 30 ms. Thereafter, you can refer to this array of strings if you need it thousands of times.

提交回复
热议问题