tags:

views:

535

answers:

2

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?

+1  A: 

Take a look at this:

http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/2ca85aa4-0672-40ad-b780-e181b28fcd80/

Posted by: Sunkyu Hwang, last reply

Gab

Gabriël
+1  A: 

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