in c#, how can i build up array from A to ZZ that is similar to the way that excel orders columns

后端 未结 10 962
情深已故
情深已故 2020-12-18 00:48

i am looking for code that can generate an array where the first item is A, then B, then C . . .after Z i

相关标签:
10条回答
  • 2020-12-18 01:31

    Found this in SO albeit in PHP. Would this help? Algorithm to get the excel-like column name of a number

    0 讨论(0)
  • 2020-12-18 01:32

    You can also try this. A to ZZ

    public class Program
    {
        public static void Main()
        {
            int c=1;
            string cc=AtoZZ(c);
            for(int i=1;i<=702;i++){
            cc=AtoZZ(i);
            Console.WriteLine(cc);
            }
        }
    
        static string AtoZZ(int chr)
        {
            char c1;
            char c2;
            string alp = "";
            if(chr<=26)
            {
                c1 = (char)(chr + 64);
                alp = c1 + "";
            }        
            else
            {
                int cl1 = chr / 26;
                int cl2 = chr % 26;
                if(cl2==0){
                    cl1--;
                    cl2=26;
                }
                c1 = (char)(cl1 + 64);
                c2 = (char)(cl2 + 64);
                alp = c1 + "" + c2;
            }
            return alp;
         }
    }
    
    0 讨论(0)
  • 2020-12-18 01:34
    var q = Enumerable.Range(Convert.ToInt32('A'),26).Select( x => Convert.ToChar(x) );
    var result = (
      q.Select( x => x.ToString() )
       .Concat( 
          q.SelectMany(
            x => q.Select( y => x.ToString() + y.ToString() )
          )
       )
    );
    
    0 讨论(0)
  • 2020-12-18 01:41

    Great answer of Vlad.

    Here's another variation on that:

     static IEnumerable<string> generate() {
       for (char c = 'A'; c <= 'Z'; c++) {
         yield return c.ToString();
       }
    
       foreach (string s in generate()) {
         for (char c = 'A'; c <= 'Z'; c++) {
           yield return s + c;
         }
       }
     }
    

    If you don't mind starting the sequence with an empty string you could write it as follows:

     static IEnumerable<string> generate() {
       yield return "";
    
       foreach (string s in generate()) {
         for (char c = 'A'; c <= 'Z'; c++) {
           yield return s + c;
         }
       }
     }
    
    0 讨论(0)
提交回复
热议问题