Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tìm chỉ số của phần tử cuối cùng trong mảng (Array) trong C#

Mục đích

Phương thức Array.GetUpperBound(int dimension) trả về chỉ số lớn nhất (upper bound) của chiều dimension trong mảng. Với mảng 1 chiều, GetUpperBound(0) = Length - 1.

Ví dụ 1: Mảng string có phần tử

using System;

public class Demo
{
    public static void Main()
    {
        string[] products = { "Andy", "Mark", "Gary", "Andre" };

        Console.WriteLine($"Có tên bắt đầu bằng 'A'? {Array.Exists(products, e => e.StartsWith("A"))}"); // True

        Console.WriteLine($"IsFixedSize: {products.IsFixedSize}");   // True
        Console.WriteLine($"IsReadOnly: {products.IsReadOnly}");     // False
        Console.WriteLine($"IsSynchronized: {products.IsSynchronized}"); // False

        Console.WriteLine($"Chỉ số phần tử đầu (GetLowerBound(0)): {products.GetLowerBound(0)}"); // 0
        Console.WriteLine($"Chỉ số phần tử cuối (GetUpperBound(0)): {products.GetUpperBound(0)}"); // 3
    }
}

Kết quả

Có tên bắt đầu bằng 'A'? True
IsFixedSize: True
IsReadOnly: False
IsSynchronized: False
Chỉ số phần tử đầu (GetLowerBound(0)): 0
Chỉ số phần tử cuối (GetUpperBound(0)): 3

Ví dụ 2: Mảng rỗng

using System;

public class Demo
{
    public static void Main()
    {
        string[] empty = Array.Empty(); // hoặc new string[0]

        Console.WriteLine($"IsFixedSize: {empty.IsFixedSize}");   // True
        Console.WriteLine($"IsReadOnly: {empty.IsReadOnly}");     // False
        Console.WriteLine($"IsSynchronized: {empty.IsSynchronized}"); // False
        Console.WriteLine($"GetLowerBound(0): {empty.GetLowerBound(0)}"); // 0
        Console.WriteLine($"GetUpperBound(0): {empty.GetUpperBound(0)}"); // -1 (rỗng)
    }
}

Kết quả

IsFixedSize: True
IsReadOnly: False
IsSynchronized: False
GetLowerBound(0): 0
GetUpperBound(0): -1

Mảng đa chiều


int[,] matrix = new int[3, 4]; // 3 hàng, 4 cột

Console.WriteLine($"Rank (số chiều): {matrix.Rank}"); // 2
Console.WriteLine($"Dim 0 (hàng): Lower={matrix.GetLowerBound(0)}, Upper={matrix.GetUpperBound(0)}"); // 0, 2
Console.WriteLine($"Dim 1 (cột): Lower={matrix.GetLowerBound(1)}, Upper={matrix.GetUpperBound(1)}"); // 0, 3
Console.WriteLine($"Total elements: {matrix.Length}"); // 12

GetLowerBound / GetUpperBound vs Length/Index

Biểu thứcGiá trị (mảng 1 chiều length=n)
GetLowerBound(0)0 (luôn)
GetUpperBound(0)n - 1
Lengthn
array[0]Phần tử đầu
array[^1] (C# 8)Phần tử cuối

Lưu ý

  • Mảng .NET **luôn zero-based** (lower bound = 0) cho các mảng tạo bằng C# syntax. Chỉ mảng tạo bởi Array.CreateInstance với lower bound tùy chỉnh mới khác 0.
  • GetUpperBound(0) == Length - 1 cho mảng 1 chiều chuẩn.
  • Dùng array.Length hoặc array.GetLength(0) cho code thông thường (rõ nghĩa hơn).
  • Array.Exists, Array.Find, Array.Sort... là static methods tiện ích.