3

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?

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at this: might helpful for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.