1

I have a method which takes a 2-dimensional array as argument.

void Process(object[,] array)
{
   // do something
}

This method can also be used for 2-dimensional arrays which have only one 'row', e.g for variables like:

object[,] flatArray = new object[N,1];

I have 1-dimensional arrays which I want to treat as 2-dimensional arrays now. The best solution I could come up with is:

private object[,] Make2D(object[] array)
{
    object[,] result = new object[array.Length, 1];
    for(int i = 0; i < array.Length; i++)
    {
        result[i, 0] = items[i];
    }
    return result;
}

Is there a more efficient / clever way to do that?

helb
  • 7,609
  • 8
  • 36
  • 58
  • You could change the enumeration rather than make a new array. A bit like this: http://stackoverflow.com/questions/10554866/how-do-you-transpose-dimensions-in-a-2d-collection-using-linq – Kaido Nov 21 '13 at 14:42

3 Answers3

1

i would advice that you use generics to avoid casting later:

private T[,] Make2D<T>(T[] array)
{
    T[,] result = new T[array.Length, 1];
    for (int i = 0; i < array.Length; i++)
    {
        result[i, 0] = array[i];
    }
    return result;
}

here is how you use it:

int[] example = new int[15];
//insert data to example
Make2D<int>(example);
helb
  • 7,609
  • 8
  • 36
  • 58
Goran Štuc
  • 581
  • 4
  • 15
  • Thanks for the hint but I'm using arrays of mixes types, so object is fine for me. However, this may help seomone else. – helb Nov 21 '13 at 14:50
1

I don't see any problems with your code.

I don't like multidimensional arrays in C#, they are difficult to work with, there is a lack of tools to work with them in the framework... example: you cannot use Array.Resize with multidimensional arrays.

I prefer to calculate indexes of a single dimension array, and simulate a multimensional array than to use multidimensional arrays. That way you can work the array with freedom, without the need for the array conversion.

Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
0
public static class Program
{
    static void Main(string[] args)
    {

        var test = new[] {1, 2, 3}.To2D();
    }

    public static T[,] To2D<T>(this T[] array)
    {
        if (array == null) throw new ArgumentNullException("array");

        var i = 0;
        var res = new T[array.Length, 1];

        Array.ForEach(array, o => res[i++, 0] = o);

        return res;
    }
}
Yaugen Vlasau
  • 2,148
  • 1
  • 17
  • 38