Reputation: 5043
I have an array of which I would like to get the length of each dimension stored in an array. I.e. I would like something like the following:
Array myArray = //...Blah blah myArray is defined somewhere in code
int[] dimLengths = myArray.SomeLinqStatement...
I can do this with some for loop(s) but I was hoping there would be a simple linq statement. So for example, if myArray is a 3D array of 2x3x4 I want dimLengths to be {2, 3, 4}.
Upvotes: 1
Views: 1419
Reputation: 460118
Why do you need LINQ to get the length of an `Array's dimensions?
myArray.GetLength(0); //returns the length of the first dimension
myArray.GetLength(1); //returns the length of the second dimension
myArray.GetLength(2); //returns the length of the third dimension
Here's your "sexy" LINQ approach:
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
var result = Enumerable.Range(0, array3D.Rank)
.Select(i => array3D.GetLength(i))
.ToArray();
Upvotes: 1
Reputation: 44326
You don't need LINQ. Here is a simple solution:
int[] GetDimensions(Array array)
{
int[] dimensions = new int[array.Rank];
for (int i = 0; i < array.Rank; i++)
{
dimensions[i] = array.GetLength(i);
}
return dimensions;
}
If you must use LINQ, you could try this, though I am sure the other way is better:
int[] dimensions = Enumerable.Range(0, array.Rank)
.Select(i => array.GetLength(i))
.ToArray();
Upvotes: 1