开发者

Printing entire array in C#

开发者 https://www.devze.com 2022-12-27 01:38 出处:网络
I have a simple 2D array: int[,] m = { {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} }; How can I print this out onto a text file or something? I want to print the entire array onto a file, not jus

I have a simple 2D array:

int[,] m = { {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} };

How can I print this out onto a text file or something? I want to print the entire array onto a file, not just the contents. For example, I don't want a bunch of zeroes all in a row: I want to see the

{{0,0,0,0,0,0,开发者_高级运维0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} };

in it.


Just iterate over it and produce the output. Something like

static string ArrayToString<T>(T[,] array)
{
    StringBuilder builder = new StringBuilder("{");

    for (int i = 0; i < array.GetLength(0); i++)
    {
        if (i != 0) builder.Append(",");
        builder.Append("{");

        for (int j = 0; j < array.GetLength(1); j++)
        {
            if (j != 0) builder.Append(",");
            builder.Append(array[i, j]);
        }

        builder.Append("}");
    }

    builder.Append("}");

    return builder.ToString();
}


There is no standard way to get those { brackets, you have to put them through the code while iterating through your array and writing them to the file

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号