tags:

views:

148

answers:

3

I know this is kind of a dumb question, but does anyone have an elegant (or non-elegant) LINQ approach to transform a 2D array (object[,]) into a 1D array (object[]) comprised of the first dimension of the 2D array?

Example:

        // I'd like to have the following array
        object[,] dim2 = {{1,1},{2,2},{3,3}};

        // converted into this kind of an array...  :)
        object[] dim1 = { 1, 2, 3 };
+4  A: 

You claim that you want a 1D array (object[]) comprised of the first dimension of the 2D array, so I assume you are trying to select a subset of the original 2D array.

int[,] foo = new int[2, 3]
{
  {1,2,3},
  {4,5,6}
};

int[] first = Enumerable.Range(0, foo.GetLength(0))
                        .Select(i => foo[i, 0])
                        .ToArray();

// first == {1, 4}
Greg
Thanks Greg, I'll try this out!
code4life
A: 

@Elisha had posted an answer (didn't compile initially) also, which I was investigating this afternoon. I don't know why he deleted his answer, but I carried on with his code example until everything got worked out, and it also gives me what I need:

object[,] dim2 = 
   {{"ADP", "Australia"}, {"CDN", "Canada"}, {"USD", "United States"}};

object[] dim1 = dim2.Cast<object>().ToArray();

// dim1 = {"ADP", "CDN", "USD"} 

This code compiles and returns the expected results. I glad about the .Cast(), and that I only needed the first dimension, not the second.

code4life
In the example here of [country_code,country_name], I would recommend using a dictionary rather than an array[,], if possible. You could then just read the keys of the dictionary to get the "first dimension".
Robert Gowland
@Robert: Yeah, good point. The problem is that the 2d array is actually being provided from an Excel VSTO Range.get_Value() call.
code4life
When I run that code, I get `dim1 = {"ADP", "Australia", "CDN", "Canada", "USD", "United States"}`
Greg
@Greg, absolutely right. Sorry about that. I was actually working with a 2-dimensional array returned from Excel. The second dimension turned out to be empty, which was why I was getting the expected results. So now I can see this is not the correct answer.
code4life
A: 

In general, for a collection of collections (instead of an array of arrays), you can do:

mainCollection.Select(subCollection => subCollection.First());
Mike F
@Mike, thanks for pointing that out. But the 2 dimensional array is being passed back from an external function, so out of my control.
code4life