Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ลิสต์ว่าง (Empty List) ใน C#: การสร้างและตรวจสอบ

List<T> ที่สร้างใหม่โดยไม่เพิ่มองค์ประกอบ จะเป็น Empty List (ลิสต์ว่าง) - ไม่ใช่ null มีขนาด (Count) เท่ากับ 0 แต่พร้อมใช้งานได้ทันที

การสร้าง Empty List

// วิธีต่างๆ ในการสร้าง Empty List
var list1 = new List();                    // Constructor แบบปกติ
var list2 = new List(0);                   // ระบุ Capacity = 0
var list3 = Enumerable.Empty().ToList();   // จาก LINQ
List list4 = [];                           // Collection Expression (C# 12+)

โค้ดตัวอย่างสมบูรณ์

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo
{
    public static void Main()
    {
        // สร้าง Empty List
        List myList = new List();
        
        Console.WriteLine($"myList == null: {myList == null}");     // False
        Console.WriteLine($"myList.Count: {myList.Count}");         // 0
        Console.WriteLine($"myList.Capacity: {myList.Capacity}");   // 0 (เริ่มต้น)
        Console.WriteLine($"myList.Any(): {myList.Any()}");         // False
        
        // เพิ่มข้อมูล
        myList.Add("First");
        Console.WriteLine($"\nหลัง Add(1 รายการ): Count={myList.Count}, Capacity={myList.Capacity}");
        
        myList.AddRange(new[] { "Second", "Third" });
        Console.WriteLine($"หลัง AddRange(2 รายการ): Count={myList.Count}, Capacity={myList.Capacity}");
        
        // เคลียร์กลับเป็น Empty
        myList.Clear();
        Console.WriteLine($"\nหลัง Clear(): Count={myList.Count}, Capacity={myList.Capacity}");
        Console.WriteLine($"ยังคงไม่ใช่ null: {myList != null}"); // True
    }
}

ผลลัพธ์

myList == null: False
myList.Count: 0
myList.Capacity: 0
myList.Any(): False

หลัง Add(1 รายการ): Count=1, Capacity=4
หลัง AddRange(2 รายการ): Count=3, Capacity=4

หลัง Clear(): Count=3, Capacity=4
ยังคงไม่ใช่ null: True

Empty List vs Null List - ความแตกต่างสำคัญ

ลักษณะEmpty List (new List())Null List (null)
Count0โยน NullReferenceException
เพิ่มข้อมูลได้ได้ไม่ได้ (Exception)
วนลูปได้ได้ (ไม่รัน body)ไม่ได้ (Exception)
LINQ (Any, Count, ฯลฯ)ทำงานได้โยน Exception
หน่วยความจำมี Object Headerไม่มี Object

Best Practices

✅ คืน Empty List แทน null

// Good: คืน Empty List
public List GetItems()
{
    if (noData) return new List(); // หรือ []
    return items;
}

// Bad: คืน null
public List GetItemsBad()
{
    if (noData) return null; // Caller ต้องเช็ค null ทุกครั้ง
}

✅ ใช้ Collection Expression (C# 12+)

List empty = [];           // สร้าง Empty List
List withItems = ["A", "B"]; // สร้างพร้อมข้อมูล

✅ ตรวจสอบว่าว่างหรือไม่

// แทนที่จะเช็ค null
if (list != null && list.Count > 0) { ... }

// ใช้ LINQ (ปลอดภัยกับ null ถ้าใช้ ?.)
if (list?.Any() == true) { ... }

// หรือ Pattern Matching (C# 11+)
if (list is { Count: > 0 }) { ... }

ข้อควรระวัง

  • Capacity ไม่ลดลงเมื่อ Clear() - ใช้ TrimExcess() หากต้องการปล่อยหน่วยความจำ
  • List<T> เป็น Reference Type - การกำหนด list1 = list2 จะชี้ไปที่อินสแตนซ์เดียวกัน
  • Empty List ไม่เท่ากับ null - new List() != null เป็น true