Reputation: 27717
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?
Upvotes: 3
Views: 2128
Reputation: 27717
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();
}
Upvotes: 2