4

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 };
2
  • 1
    Sample input and output would make it easier to interpret your question correct. Commented Apr 7, 2010 at 18:48
  • Ok - added example as you requested! Commented Apr 7, 2010 at 20:03

3 Answers 3

6

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}
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

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: Yeah, good point. The problem is that the 2d array is actually being provided from an Excel VSTO Range.get_Value() call.
When I run that code, I get dim1 = {"ADP", "Australia", "CDN", "Canada", "USD", "United States"}
@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.
0

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

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

1 Comment

@Mike, thanks for pointing that out. But the 2 dimensional array is being passed back from an external function, so out of my control.

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.