简体   繁体   English

.NET 多维数组打印

[英].NET Multi Dimensional Array Printing

Let's say I have a .NET Array of n number of dimensions.假设我有一个 n 维数的 .NET 数组。 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.我可以使用一些 Rank 和维度函数编写一个循环来计算索引。 Is there a built in function instead?有内置函数吗?

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

看看这个:可能对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM