ภาพรวม
Array.GetLength(int dimension) คืนจำนวนสมาชิกในมิติที่ระบุ (0-based) สำหรับอาร์เรย์ 1 มิติ ใช้ GetLength(0) หรือ property Length
ตัวอย่างที่ 1: อาร์เรย์สตริง 6 ค่า ตรวจสอบความยาวและค้นหาด้วย Exists
using System;
public class Demo
{
public static void Main()
{
string[] products = { "Electronics", "Accessories", "Clothing", "Toys", "Clothing", "Furniture" };
Console.WriteLine("Products list...");
foreach (string s in products)
{
Console.WriteLine(s);
}
Console.WriteLine("Array length = " + products.GetLength(0));
Console.WriteLine("\nOne or more products begin with 'C'? = {0}", Array.Exists(products, ele => ele.StartsWith("C")));
Console.WriteLine("One or more products begin with 'D'? = {0}", Array.Exists(products, ele => ele.StartsWith("D")));
Console.WriteLine("One or more products begin with 'T'? = {0}", Array.Exists(products, ele => ele.StartsWith("T")));
Console.WriteLine("One or more products begin with 'E'? = {0}", Array.Exists(products, ele => ele.StartsWith("E")));
}
}
ผลลัพธ์
Products list... Electronics Accessories Clothing Toys Clothing Furniture Array length = 6 One or more products begin with 'C'? = True One or more products begin with 'D'? = False One or more products begin with 'T'? = True One or more products begin with 'E'? = True
ตัวอย่างที่ 2: อาร์เรย์ว่าง ตรวจสอบ IsFixedSize และ IsReadOnly
using System;
public class Demo
{
public static void Main()
{
string[] products = new string[] { };
Console.WriteLine("Array length = " + products.GetLength(0));
Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
}
}
ผลลัพธ์
Array length = 0 Is the array having fixed size? = True Is the array read only? = False
สรุป
LengthหรือGetLength(0)ใช้ได้กับอาร์เรย์ 1 มิติ- อาร์เรย์ใน C# มีขนาดคงที่ (IsFixedSize = true)
Array.Exists()ใช้ predicate (lambda) ค้นหาเงื่อนไข- อาร์เรย์ไม่ใช่ read-only (สามารถเปลี่ยนค่าแต่ละช่องได้)