Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LINQ on a multidimensional array to 'unwind' the array?

Consider the following array:

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

I would like to use LINQ to construct an IEnumerable with numbers 2, 1, 3, 4, 6, 5.

What would be the best way to do so?

like image 987
Kees C. Bakker Avatar asked Dec 11 '12 15:12

Kees C. Bakker


People also ask

Does LINQ work on arrays?

LINQ allows us to write query against all data whether it comes from array, database, XML etc. This is the best feature of LINQ.

How do you handle multidimensional arrays?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays.

How do multidimensional arrays work C#?

C# supports multidimensional arrays up to 32 dimensions. The multidimensional array can be declared by adding commas in the square brackets. For example, [,] declares two-dimensional array, [, ,] declares three-dimensional array, [, , ,] declares four-dimensional array, and so on.


3 Answers

Use simple foreach to get your numbers from 2d array:

int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };
foreach(int x in numbers)
{
   // 2, 1, 3, 4, 6, 5.
}

LINQ (it's an big overhead to use Linq for your initial task, because instead of simple iterating array, CastIterator (Tim's answer) of OfTypeIterator will be created)

IEnumerable<int> query = numbers.OfType<int>();
like image 103
Sergey Berezovskiy Avatar answered Oct 18 '22 17:10

Sergey Berezovskiy


Perhaps simply:

var all = numbers.Cast<int>();

Demo

like image 28
Tim Schmelter Avatar answered Oct 18 '22 17:10

Tim Schmelter


How about:

Enumerable
    .Range(0,numbers.GetUpperBound(0)+1)
    .SelectMany(x => Enumerable.Range(0,numbers.GetUpperBound(1)+1)
    .Select (y =>numbers[x,y] ));

or to neaten up.

var xLimit=Enumerable.Range(0,numbers.GetUpperBound(0)+1);
var yLimit=Enumerable.Range(0,numbers.GetUpperBound(1)+1);
var result = xLimit.SelectMany(x=> yLimit.Select(y => numbers[x,y]));

EDIT Revised Question....

var result = array.SelectMany(x => x.C);
like image 7
Bob Vale Avatar answered Oct 18 '22 17:10

Bob Vale