บทความนี้สาธิตวิธีตรวจสอบว่า Array มีขนาดคงที่ (fixed size) หรือไม่ โดยใช้คุณสมบัติ IsFixedSize ใน C# — พร้อมตัวอย่างการค้นหาข้อมูลด้วย Array.Exists()
ตัวอย่างที่ 1: อาเรย์สตริงพร้อมตรวจสอบหลายเงื่อนไข
using System;
public class Demo
{
public static void Main()
{
string[] products = new string[] { "Electronics", "Accessories", "Clothing", "Toys", "Clothing", "Furniture" };
Console.WriteLine("Products list...");
foreach (string s in products)
{
Console.WriteLine(s);
}
Console.WriteLine("Is the products Accessories in the array? = {0}",
Array.Exists(products, ele => ele == "Accessories"));
Console.WriteLine("Is the products Stationery in the array? = {0}",
Array.Exists(products, ele => ele == "Stationery"));
Console.WriteLine("\nOne or more products begin with the letter 'C'? = {0}",
Array.Exists(products, ele => ele.StartsWith("C")));
Console.WriteLine("One or more planets begin with 'D'? = {0}",
Array.Exists(products, ele => ele.StartsWith("D")));
Console.WriteLine("One or more products begin with the letter 'T'? = {0}",
Array.Exists(products, ele => ele.StartsWith("T")));
Console.WriteLine("One or more planets begin with 'E'? = {0}",
Array.Exists(products, ele => ele.StartsWith("E")));
Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
}
}
ผลลัพธ์
Products list... Electronics Accessories Clothing Toys Clothing Furniture Is the products Accessories in the array? = True Is the products Stationery in the array? = False One or more products begin with the letter 'C'? = True One or more planets begin with 'D'? = False One or more products begin with the letter 'T'? = True One or more planets begin with 'E'? = True Is the array having fixed size? = True
ตัวอย่างที่ 2: อาเรย์ว่าง — ตรวจสอบคุณสมบัติพื้นฐาน
using System;
public class Demo
{
public static void Main()
{
string[] products = new string[] { };
Console.WriteLine("One or more planets begin with 'E'? = {0}",
Array.Exists(products, ele => ele.StartsWith("E")));
Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
}
}
ผลลัพธ์
One or more planets begin with 'E'? = False Is the array having fixed size? = True
สรุป
- คุณสมบัติ
IsFixedSizeของอาเรย์จะคืนค่าtrueเสมอ — อาเรย์ใน C# มีขนาดคงที่ตลอดชีวิต (ไม่สามารถเพิ่ม/ลบขนาดได้หลังสร้าง) - คุณสมบัติ
IsReadOnlyจะคืนค่าfalseเสมอ — อาเรย์สามารถแก้ไขสมาชิกได้ (แต่ไม่สามารถเปลี่ยนขนาดได้) - เมธอด
Array.Exists<T>(T[] array, Predicate<T> match)ใช้ตรวจสอบว่ามีสมาชิกอย่างน้อย 1 ตัวตรงเงื่อนไขหรือไม่ - Lambda expression เช่น
ele => ele.StartsWith("C")ใช้กำหนดเงื่อนไขการค้นหา - หากต้องการคอลเลกชันที่ขยายขนาดได้ (resizeable) ให้ใช้
List<T>แทน
ตัวอย่างเพิ่มเติม: Array.Exists กับเงื่อนไขต่างๆ
int[] numbers = { 1, 3, 5, 7, 9, 10, 12 };
bool hasEven = Array.Exists(numbers, n => n % 2 == 0); // true (มี 10, 12)
bool allOdd = Array.TrueForAll(numbers, n => n % 2 != 0); // false (มีเลขคู่)
int firstEven = Array.Find(numbers, n => n % 2 == 0); // 10
int[] allEvens = Array.FindAll(numbers, n => n % 2 == 0); // {10, 12}