How to print 2D array to console in C#

2019-02-21 06:49发布

I dont't have any code for this, but I do want to know how I could do this. I use visual studio 2010 C# if that matters.

Thanks

Jason

9条回答
Root(大扎)
2楼-- · 2019-02-21 07:15

Try like this..

        int[,] matrix = new int[3, 3]
        {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9},
        };

        int rowLength = matrix.GetLength(0);
        int colLength = matrix.GetLength(1);

        for (int i = 0; i < rowLength; i++)
        {
            for (int j = 0; j < colLength; j++)
            {
                Console.Write(string.Format("{0} ", matrix[i, j]));
            }
            Console.Write(Environment.NewLine + Environment.NewLine);
        }


        Console.Read();
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-21 07:17

You should read MSDN:Using foreach with Arrays

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

// Output: 9 99 3 33 5 55

查看更多
相关推荐>>
4楼-- · 2019-02-21 07:22

you can print it all on one line

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Console.WriteLine(String.Join(" ", array2D.Cast<int>()));

output

1 2 3 4 5 6 7 8
查看更多
登录 后发表回答