Question

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?

Was it helpful?

Solution

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();
}

OTHER TIPS

Take a look at this: might helpful for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top