LINQ: Convert Array [,] to Array []

I know this is kind of a dumb question, but someone has an elegant (or not elegant) LINQ approach to convert a 2D array (object [,]) to a 1D array (object []), consisting of the first 2D size 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 };
+3
source share
3 answers

You claim you want a 1D array (object[]) comprised of the first dimension of the 2D array, so I assume that 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}
+6
source

@Elisha also posted an answer (also did not compile), which I investigated this afternoon. I don’t know why he deleted his answer, but I continued his code example until everything 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"} 

. .Cast(), first, .

0

( ) :

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

Source: https://habr.com/ru/post/1740205/


All Articles