Yu Zhang
Yu Zhang

Reputation: 2149

How to pass a multi-dimensional array to a function?

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

Upvotes: 2

Views: 273

Answers (2)

Jowe
Jowe

Reputation: 63

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

Upvotes: 3

Evk
Evk

Reputation: 101453

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

Upvotes: 3

Related Questions