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

วิธีล้างข้อมูล List ใน C#

ใช้เมธอด Clear() เพื่อล้างข้อมูลใน List

ขั้นแรก สร้าง List และเพิ่มข้อมูล:

List<string> myList = new List<string>() {
    "one", "two", "three", "four", "five", "six"
};

ล้าง List:

myList.Clear();

ตัวอย่าง

using System;
using System.Collections.Generic;
public class Program {
    public static void Main() {
        List<string> myList = new List<string>() {
            "one", "two", "three", "four", "five", "six"
        };
        foreach(string str in myList) {
            Console.WriteLine(str);
        }
        Console.WriteLine("Elements in the list = " + myList.Count);
        // ล้าง List
        myList.Clear();
        Console.WriteLine("Elements in the list after using Clear() = " + myList.Count);
    }
}

ผลลัพธ์

one
two
three
four
five
six
Elements in the list = 6
Elements in the list after using Clear() = 0