2

In C#, I need to pass a multi-dimensional integer array to a method, but the actual dimension of this array is unknown until run time, how do I achieve this?

For example, the input can be:

  1. {1,2,3}
  2. {1,2,{1}}
  3. {1{1,2,3,}2,2,{6,{4,{1,2,3,4}}}}

Basically, I am trying to flatten a multi-dimensional array. For example, the input of my method is: {1{1,2,3,}2,2,{6,{4,{1,2,3,4}}}}, the output will be {1,1,2,3,2,2,6,4,1,2,3,4}

I have come up with the following unfinished code block:

public void Recursive(multiple-dimension-integer-array)
{
    foreach (var element in multiple-dimension-integer-array)
    {
        if (element is int)
            result.Add(element);
        else Recursive(element);
    }
}
2
  • 1
    Please provide some sample code and show us the error you are getting, and state what you expect to happen. That way we can provide the best answer to you. Commented Feb 20, 2018 at 5:54
  • @PhillipNgan, added. Commented Feb 20, 2018 at 5:59

2 Answers 2

3

All arrays (including multidimensional and jagged) implicitly inherit from Array class, so you can use that class to accept them all:

public class Program {
    public static void Main() {
        int[,,] multidim = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
            { { 7, 8, 9 }, { 10, 11, 12 } } };
        int[][] jagged = new int[3][];
        jagged[0] = new int[] { 1, 3, 5, 7, 9 };
        jagged[1] = new int[] { 0, 2, 4, 6 };
        jagged[2] = new int[] { 11, 22 };

        var result = Flatten<int>(multidim);
        Console.WriteLine(String.Join(", ", result));
        result = Flatten<int>(jagged);
        Console.WriteLine(String.Join(", ", result));
        Console.ReadKey();
    }

    public static IEnumerable<T> Flatten<T>(Array a) {
        foreach (var item in a) {
            if (item is Array) {
                foreach (var sub in Flatten<T>((Array) item))
                    yield return sub;
            }
            else {
                yield return (T) item;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was thinking about using "params" to accept an array, silly me.
3

Pass as an Array and cast non-ints.

private void Main()
{
    object[] a = {1,2,3};
    object[] b = {4,5,a};
    Recursive(b);
}

// mdia = multiple-dimension-integer-array
public void Recursive(Array mdia)
{
    foreach (var element in mdia)
    {
        if (element is int)
            result.Add(element);
        else
            Recursive((Array)element);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.