ใน C# มีหลายวิธีในการตรวจสอบว่า List<T> ว่าง (Empty) หรือไม่ วิธีที่แนะนำและทันสมัยที่สุดคือใช้ LINQ Any() หรือ Property Count
วิธีที่ 1: ใช้ LINQ Any() (แนะนำ)
using System;
using System.Collections.Generic;
using System.Linq;
var subjects = new List(); // Empty list
// subjects.Add("Maths"); // ถ้าเพิ่มข้อมูล
// Any() คืน true ถ้ามีอย่างน้อย 1 รายการ
bool isEmpty = !subjects.Any();
if (isEmpty) {
Console.WriteLine("Empty");
} else {
Console.WriteLine("List is not empty");
}
วิธีที่ 2: ใช้ Count Property (เร็วที่สุด)
var subjects = new List();
// Count เป็น Property O(1) - เร็วที่สุด
bool isEmpty = subjects.Count == 0;
// หรือ
if (subjects.Count == 0) {
Console.WriteLine("Empty");
}
วิธีที่ 3: ใช้ Count Extension Method (LINQ)
// Count() เป็น Method - อาจช้ากว่า Property เล็กน้อย
bool isEmpty = subjects.Count() == 0;
ตัวอย่างโค้ดสมบูรณ์
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main(string[] args) {
var subjects = new List();
subjects.Add("Maths");
subjects.Add("Java");
subjects.Add("English");
subjects.Add("Science");
subjects.Add("Physics");
subjects.Add("Chemistry");
foreach (var sub in subjects) {
Console.WriteLine(sub);
}
// ตรวจสอบว่าว่างหรือไม่
bool isEmpty = !subjects.Any();
if (isEmpty) {
Console.WriteLine("Empty");
} else {
Console.WriteLine("List is not empty");
}
}
}
ผลลัพธ์
Maths
Java
English
Science
Physics
Chemistry
List is not empty
เปรียบเทียบประสิทธิภาพ
| Method | Time Complexity | Allocation | แนะนำ? |
|---|---|---|---|
list.Count == 0 |
O(1) | ไม่มี | ✅ เร็วที่สุด |
!list.Any() |
O(1) - หยุดทันทีเจอตัวแรก | Enumerator (struct) | ✅ อ่านง่าย, Generic |
list.Count() == 0 |
O(1) สำหรับ List (มี Optimization) | Enumerator | ⚠️ ใช้ได้แต่ไม่จำเป็น |
list.Count > 0 |
O(1) | ไม่มี | ✅ สำหรับเช็คว่ามีข้อมูล |
สำหรับ Collection อื่นๆ (IEnumerable, Array, etc.)
// Array
int[] arr = new int[0];
bool empty = arr.Length == 0;
// IEnumerable (ไม่รู้ขนาดล่วงหน้า)
IEnumerable enum = GetNumbers();
bool empty2 = !enum.Any(); // ต้อง Iterate หาตัวแรก
// ICollection / IList
ICollection coll = new List();
bool empty3 = coll.Count == 0;
Extension Method สำหรับอ่านง่ายขึ้น
public static class ListExtensions {
public static bool IsEmpty<T>(this List<T> list)
=> list.Count == 0;
public static bool IsNullOrEmpty<T>(this List<T> list)
=> list == null || list.Count == 0;
}
// ใช้งาน
if (subjects.IsEmpty()) Console.WriteLine("Empty");
if (subjects.IsNullOrEmpty()) Console.WriteLine("Null or Empty");
Best Practices
- ใช้
Count == 0สำหรับList<T>โดยตรง - เร็วที่สุด - ใช้
!Any()สำหรับIEnumerable<T>ทั่วไป - Generic และ Short-circuit - หลีกเลี่ยง
Count() == 0บน IEnumerable ที่ไม่ใช่ ICollection - อาจต้อง Iterate ทั้งหมด - ตรวจสอบ
nullก่อนถ้าตัวแปรอาจเป็น Null:list?.Count == 0หรือlist.IsNullOrEmpty()