2D array to table in c#?

前端 未结 3 1058
渐次进展
渐次进展 2021-01-29 10:36

I need to put the data from this table into an array and then make the array print as a formatted table in the console. Here\'s the table that I got my data from http://puu.sh/

3条回答
  •  -上瘾入骨i
    2021-01-29 11:09

    Foreach on a [,] array gives you all elements as a list, as you noticed. In this case you need to output as follow:

    for (int x0 = 0; x0 < schedule.GetLength(0); x0++)
    {
        for (int x1 = 0; x1 < schedule.GetLength(1); x1++)
        {
            Console.Write("{0}\t", schedule[x0, x1]);
        }
        Console.WriteLine();
    }
    Console.ReadKey();
    

    If you want to use foreach for any reason, you can also declare your table as [][] array. But in both ways you have to create 2 loops:

    string[][] schedule = new string[][] {
                                        new string[] { "1:00", "3:00", "5:00", "7:00", "TOTAL", "", },
                                        new string[] {"Monday", "12", "10", "17", "22", "244",   },
                                        new string[] {"Tuesday", "11", "13", "17", "22", "252",},
                                        new string[] {"Wednesday", "12", "10", "22", "22", "264",},
                                        new string[] {"Thursday", "9", "14", "17", "22", "248",},
                                        new string[] {"Friday", "12", "10", "21", "12", "220",},
                                        new string[] {"Saturday", "12", "10", "5", "10", "148"},
                                        new string[] {" ", " ", " ", " ", " ","1376",}
            };
    foreach (string[] line in schedule)
    {
        foreach (string i in line)
            Console.Write("{0}\t", i);
        Console.WriteLine();
    }
    

提交回复
热议问题