ในการเริ่มต้นรายการเป็นรายการว่างใน C# ให้ตั้งค่าเหมือนคำสั่งต่อไปนี้โดยไม่มีองค์ประกอบใด ๆ -
List<string> list = new List<string>();
ตอนนี้ ใช้วิธี Any() เพื่อตรวจสอบว่ารายการว่างหรือไม่ -
bool chk = !list.Any();
ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static void Main() {
// empty list
List<string> list = new List<string>();
// check for empty list
bool chk = !list.Any();
if(chk) {
Console.WriteLine("List is Empty!");
} else {
Console.WriteLine("List isn't Empty!");
}
}
} ผลลัพธ์
List is Empty!