code4life
code4life

Reputation: 15794

LINQ: transform an array [,] into array[]

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

Upvotes: 4

Views: 2502

Answers (3)

Mike Asdf
Mike Asdf

Reputation: 2329

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

mainCollection.Select(subCollection => subCollection.First());

Upvotes: 0

code4life
code4life

Reputation: 15794

@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.

Upvotes: 0

Greg
Greg

Reputation: 23493

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}

Upvotes: 6

Related Questions