Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Multi Dimensional Array Printing

Tags:

arrays

c#

.net

Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:

[0, 0, 0] = 2
[0, 0, 1] = 32

And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?

like image 221
Jake Pearson Avatar asked Dec 14 '25 21:12

Jake Pearson


1 Answers

Thanks for the answer, here is what I wrote while I waited:

public static string Format(Array array)
{
    var builder = new StringBuilder();
    builder.AppendLine("Count: " + array.Length);
    var counter = 0;

    var dimensions = new List<int>();
    for (int i = 0; i < array.Rank; i++)
    {
        dimensions.Add(array.GetUpperBound(i) + 1);
    }

    foreach (var current in array)
    {
        var index = "";
        var remainder = counter;
        foreach (var bound in dimensions)
        {
            index = remainder % bound + ", " + index;
            remainder = remainder / bound;
        }
        index = index.Substring(0, index.Length - 2);

        builder.AppendLine("   [" + index + "] " + current);
        counter++;
    }
    return builder.ToString();
}
like image 87
Jake Pearson Avatar answered Dec 17 '25 09:12

Jake Pearson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!