Clear() मेथड से लिस्ट खाली करना
C# लिस्ट को खाली करने के लिए Clear() मेथड का उपयोग करें।
लिस्ट बनाएं और एलिमेंट्स जोड़ें:
List<string> myList = new List<string>() {
"one", "two", "three", "four", "five", "six"
};
लिस्ट खाली करें:
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);
// लिस्ट खाली करें
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
महत्वपूर्ण बिंदु:
Clear()सभी एलिमेंट्स हटा देता है लेकिन कैपेसिटी बरकरार रखता हैCount0 हो जाता है,Capacityअपरिवर्तित रहता है- नई लिस्ट असाइन करने से (
myList = new List<string>()) कैपेसिटी भी रीसेट हो जाती है TrimExcess()कैपेसिटी को Count के बराबर कर सकता है
संबंधित मेथड्स:
myList.Remove("two") // विशिष्ट आइटम हटाएं
myList.RemoveAt(0) // इंडेक्स पर हटाएं
myList.RemoveAll(x => x.Length > 3) // शर्त के आधार पर हटाएं