C# में List<T> वर्ग की RemoveRange(int index, int count) विधि का उपयोग करके निर्दिष्ट सूचकांक से शुरू होने वाले तत्वों की एक श्रेणी को हटाया जा सकता है। यह विधि एक बार में कई तत्वों को कुशलतापूर्वक हटाती है।
उदाहरण 1: सूचकांक 1 से 3 तत्व हटाना
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List list1 = new List();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("List1 में तत्व...");
foreach (string res in list1) {
Console.WriteLine(res);
}
List list2 = new List();
list2.Add("India");
list2.Add("US");
list2.Add("UK");
list2.Add("Canada");
list2.Add("Poland");
list2.Add("Netherlands");
Console.WriteLine("List2 में तत्व...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("\nक्या List2, List1 के बराबर है? = " + list2.Equals(list1));
Console.WriteLine("\nlist2 में तत्वों की संख्या = " + list2.Count);
list2.RemoveRange(1, 3);
Console.WriteLine("\nlist2 में तत्वों की संख्या (अपडेटेड) = " + list2.Count);
Console.WriteLine("List2 में तत्व... अपडेटेड");
foreach (string res in list2) {
Console.WriteLine(res);
}
}
}
आउटपुट
List1 में तत्व... One Two Three Four Five List2 में तत्व... India US UK Canada Poland Netherlands क्या List2, List1 के बराबर है? = False list2 में तत्वों की संख्या = 6 list2 में तत्वों की संख्या (अपडेटेड) = 3 List2 में तत्व... अपडेटेड India Poland Netherlands
उदाहरण 2: एकाधिक RemoveRange कॉल
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List list = new List();
list.Add("India");
list.Add("US");
list.Add("UK");
list.Add("Canada");
list.Add("Poland");
list.Add("Netherlands");
list.Add("Bhutan");
list.Add("Singapore");
Console.WriteLine("List में तत्व...");
foreach (string res in list) {
Console.WriteLine(res);
}
Console.WriteLine("\nList में तत्वों की संख्या = " + list.Count);
list.RemoveRange(1, 3);
Console.WriteLine("\nList में तत्वों की संख्या (अपडेटेड) = " + list.Count);
Console.WriteLine("List में तत्व... अपडेटेड");
foreach (string res in list) {
Console.WriteLine(res);
}
list.RemoveRange(2, 3);
Console.WriteLine("\nList में तत्वों की संख्या (फिर अपडेटेड) = " + list.Count);
Console.WriteLine("List में तत्व... फिर अपडेटेड");
foreach (string res in list) {
Console.WriteLine(res);
}
}
}
आउटपुट
List में तत्व... India US UK Canada Poland Netherlands Bhutan Singapore List में तत्वों की संख्या = 8 List में तत्वों की संख्या (अपडेटेड) = 5 List में तत्व... अपडेटेड India Poland Netherlands Bhutan Singapore List में तत्वों की संख्या (फिर अपडेटेड) = 2 List में तत्व... फिर अपडेटेड India Poland
मुख्य बिंदु
RemoveRange(index, count)- index से शुरू करके count तत्व हटाता है- यदि index या count अमान्य है तो
ArgumentOutOfRangeExceptionफेंकता है - शेष तत्व स्वचालित रूप से शिफ्ट हो जाते हैं
- समय जटिलता O(n) है जहाँ n शेष तत्वों की संख्या है
Clear()सभी तत्व हटाने के लिए उपयोग करें