Вопрос


I have a multidimensional jagged string array:

string[,][] MDJA = 
{
    {new string[]{"a", "b"}, new string[]{"c", "d"}, new string[]{"e", "f"}},
    {new string[]{"g", "h"}, new string[]{"j", "i"}, new string[]{"k", "l"}},
    {new string[]{"m", "n"}, new string[]{"o", "p"}, new string[]{"q", "r"}}
}

I'm using for-loops to compare the placement of the arrays inside the array to get the array I'm looking for, but the MDJA is inside a method and i would like it to return the specific array. As an example i might want to return

new string[]{"m", "n"}

Normally I would do this in a multidimensional-array:

for (byte i = 0; i < 3; i++)
{
    if (var1[x] == var2[i])
    {
        return answers[y,i]
    }
}

But i haven't used jagged arrays before and when using them multidimensionally it made it harder to get information.

P.S The 4 variables are arguments in the method, var1 and var2 are string arrays and x/y are integers.

Thank you for helping.

Это было полезно?

Решение

I am not quite sure what your method logic looks like but regarding element access it should be quite trivial:

for (int i = 0; i < MDJA.GetLength(0); i++)
{
    for (int j = 0; j < MDJA.GetLength(1); j++)
    {
        // Your compare logics go here
        //
        bool found = i == 2 && j == 0;
        if (found)
        {
            return MDJA[i, j];
        }
    }
}

This will return the string[]{"m", "n"}.

Другие советы

I've done this before, alas I do not have the code here with me.

Build a utility method that calls itself recursively, tests whether an array element is an array itself, if it is not (and so a value) add it to a List, otherwise pass the sub/child array to the recursive method.

Hint, use Array object as the parameter for this method, rather than a defined int[,][] array, thus any form of crazy int[,][][][,,,][][,] can be passed and will still work.

And for your problem, you would have to detect at what level you wish to stop transforming from jagged arrays to values, and then returning those jagged arrays, in a simplified array.

I will post my code later, it may help you.

    public static int Count(Array pValues)
    {
        int count = 0;

        foreach(object value in pValues)
        {
            if(value.GetType().IsArray)
            {
                count += Count((Array) value);
            }
            else
            {
                count ++;
            }
        }

        return count;
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top