Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs

Dashboard
Notifications
Mark all as read
Q&A

Get the length of a slice from a multi-dimensional array

+4
−0

If I have a one-dimensional array, I can get the length of it quite easily: var x = moves.Length().

However, if the array is multi-dimensional, .Length() returns the total number of elements. If moves is defined as int[4,2], the moves.Length() returns 8.

Is there a way that I can specify either the X or Y and get the number of elements for that slice?

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Array.GetUpperBound (3 comments)

2 answers

+4
−0

I think what you are looking for is Array.GetLength which:

gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

+1
−0

You can use Array.GetUpperBound method

Gets the index of the last element of the specified dimension in the array.

and Array.GetLowerBound one accordingly.

var arr = new int[,]{
    { 1, 2 },
    { 23, 42 }
};

for (int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0); i++)
{
    for (int j = arr.GetLowerBound(0); j <= arr.GetUpperBound(1); j++)
    {
        Console.Write($"{arr[i, j],3} ");
    }
    Console.WriteLine();
}

The key difference between this method and Array.GetLength one is that GetUpperBound can be used in case when bounds of an array are arbitrary:

var arrWithNonStandardBounds =
    Array.CreateInstance(
        typeof(ValueTuple<int, int>),
        new[] { 2, 2, },
        new int[] { -1, -1 }
    );

var n = arrWithNonStandardBounds.GetUpperBound(0);
var m = arrWithNonStandardBounds.GetUpperBound(1);

for (int i = arrWithNonStandardBounds.GetLowerBound(0); i <= n; i++)
{
    for (int j = arrWithNonStandardBounds.GetLowerBound(1); j <= m; j++)
    {
        arrWithNonStandardBounds.SetValue((i, j), i, j);
        Console.Write($"{arrWithNonStandardBounds.GetValue(i, j),5} ");
    }
    Console.WriteLine();
}

It's a rare case especially lately though.

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »