Giới thiệu
Phần tử cuối cùng của mảng ở chỉ số Length - 1 (0-based indexing). Truy cập: arr[arr.Length - 1].
Ví dụ cơ bản
string[] str = { "Java", "HTML", "jQuery", "JavaScript", "Bootstrap" };
string last = str[str.Length - 1]; // "Bootstrap"
Ví dụ hoàn chỉnh
using System;
public class Demo
{
public static void Main()
{
string[] str = { "Java", "HTML", "jQuery", "JavaScript", "Bootstrap" };
Console.WriteLine("Array...");
foreach (string res in str) Console.WriteLine(res);
Console.WriteLine("Last element: " + str[str.Length - 1]);
}
}
Kết quả
Array... Java HTML jQuery JavaScript Bootstrap Last element: Bootstrap
Các cách khác lấy phần tử cuối
- LINQ Last():
str.Last()(cầnusing System.Linq;), ném ngoại lệ nếu rỗng. - LINQ LastOrDefault():
str.LastOrDefault()trả về null/default nếu rỗng. - Index từ cuối (C# 8+):
str[^1]- index from end operator. - Array.GetValue:
arr.GetValue(arr.Length - 1)(boxing cho value type).
Ví dụ C# 8+ Index from end
string[] arr = { "a", "b", "c" };
Console.WriteLine(arr[^1]); // "c" (last)
Console.WriteLine(arr[^2]); // "b" (second to last)
Console.WriteLine(arr[arr.Length - 1]); // Traditional
Lưu ý an toàn