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?
LINQ allows us to write query against all data whether it comes from array, database, XML etc. This is the best feature of LINQ.
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.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays.
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.
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>();
Perhaps simply:
var all = numbers.Cast<int>();
Demo
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With