C# में HashSet<T> वर्ग की Remove(T) विधि का उपयोग करके निर्दिष्ट तत्व को हटाया जा सकता है। चूंकि HashSet में डुप्लिकेट नहीं होते, यह विधि तत्व मौजूद होने पर उसे हटाकर true लौटाती है, अन्यथा false।
उदाहरण 1: स्ट्रिंग HashSet से तत्व हटाना
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
HashSet set1 = new HashSet();
set1.Add("AB");
set1.Add("CD");
set1.Add("EF");
set1.Add("AB"); // डुप्लिकेट - अनदेखा होगा
set1.Add("IJ");
set1.Add("KL");
set1.Add("EF"); // डुप्लिकेट - अनदेखा होगा
set1.Add("OP");
Console.WriteLine("HashSet1 में तत्व");
foreach(string val in set1) {
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add("EF");
set2.Add("KL");
Console.WriteLine("HashSet2 में तत्व");
foreach(string val in set2) {
Console.WriteLine(val);
}
Console.WriteLine("HashSet2 में तत्वों की संख्या = " + set2.Count);
set2.Remove("KL");
Console.WriteLine("\nHashSet2 में तत्व... (अपडेटेड)");
foreach (string res in set2) {
Console.WriteLine(res);
}
Console.WriteLine("HashSet2 में तत्वों की संख्या (अपडेटेड) = " + set2.Count);
Console.WriteLine("\nक्या set1, set2 का सुपरसेट है? " + set1.IsSupersetOf(set2));
}
}
आउटपुट
HashSet1 में तत्व AB CD EF IJ KL OP HashSet2 में तत्व EF KL HashSet2 में तत्वों की संख्या = 2 HashSet2 में तत्व... (अपडेटेड) EF HashSet2 में तत्वों की संख्या (अपडेटेड) = 1 क्या set1, set2 का सुपरसेट है? True
उदाहरण 2: पूर्णांक HashSet से तत्व हटाना
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
HashSet set1 = new HashSet();
set1.Add(100);
set1.Add(200);
set1.Add(300);
set1.Add(400);
set1.Add(500);
set1.Add(600);
Console.WriteLine("HashSet में तत्व");
foreach(int val in set1) {
Console.WriteLine(val);
}
Console.WriteLine("HashSet में तत्वों की संख्या = " + set1.Count);
set1.Remove(300);
Console.WriteLine("\nHashSet में तत्व... (अपडेटेड)");
foreach (int res in set1) {
Console.WriteLine(res);
}
Console.WriteLine("HashSet में तत्वों की संख्या (अपडेटेड) = " + set1.Count);
}
}
आउटपुट
HashSet में तत्व 100 200 300 400 500 600 HashSet में तत्वों की संख्या = 6 HashSet में तत्व... (अपडेटेड) 100 200 400 500 600 HashSet में तत्वों की संख्या (अपडेटेड) = 5
मुख्य बिंदु
HashSet<T>डुप्लिकेट मान संग्रहीत नहीं करताRemove(T)तत्व मौजूद होने परtrueलौटाता है- औसत समय जटिलता O(1) है
IsSupersetOf(),IsSubsetOf()आदि सेट ऑपरेशन उपलब्ध हैं