Domanda

Diciamo che ho un array .NET di n numero di dimensioni.Vorrei analizzare gli elementi e stampare qualcosa del tipo:

[0, 0, 0] = 2
[0, 0, 1] = 32

E così via.Potrei scrivere un ciclo utilizzando alcune funzioni di rango e dimensione per ottenere gli indici.Esiste invece una funzione integrata?

È stato utile?

Soluzione

Grazie per la risposta, ecco cosa ho scritto mentre aspettavo:

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

Altri suggerimenti

Guarda questo: potrebbe esserti utile.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top