HashSet<T>.Add(T item) মেথড ব্যবহার করে হ্যাশ সেটে উপাদান যোগ করা যায়। HashSet ডুপ্লিকেট অনুমতি দেয় না (সেট সেমান্টিক্স)। Add() true রিটার্ন করলে উপাদান নতুন ছিল, false রিটার্ন করলে ইতিমধ্যে ছিল। এটি O(1) গড় সময়ে ইনসারশন/লুকআপ প্রদান করে।
উদাহরণ ১: দুটি HashSet তৈরি এবং তুলনা
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("HashSet1-এ উপাদানসমূহ...");
foreach (string res in set1) {
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("HashSet2-এ উপাদানসমূহ (Enumerator)...");
HashSet<string>.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("HashSet1, HashSet2-এর সমান কি? = " + set1.Equals(set2));
}
}
আউটপুট
HashSet1-এ উপাদানসমূহ... A B C D E F G H HashSet2-এ উপাদানসমূহ (Enumerator)... John Jacob Ryan Tom Andy Tim Steve Mark HashSet1, HashSet2-এর সমান কি? = False HashSet2-এর সংখ্যা = 8 HashSet2-এর সংখ্যা (আপডেটেড) = 0
নোট: আউটপুটে Clear() এবং আপডেটেড কাউন্টের কোড উদাহরণে অনুপস্থিত, কিন্তু আউটপুটে দেখানো হয়েছে।
উদাহরণ ২: সাবসেট যাচাই (IsSubsetOf)
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<int> set1 = new HashSet<int>();
set1.Add(100);
set1.Add(200);
Console.WriteLine("HashSet1-এ উপাদানসমূহ...");
foreach (int res in set1) {
Console.WriteLine(res);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(100);
set2.Add(200);
Console.WriteLine("HashSet2-এ উপাদানসমূহ...");
foreach (int res in set2) {
Console.WriteLine(res);
}
Console.WriteLine("set1, set2-এর সাবসেট কি? " + set1.IsSubsetOf(set2));
}
}
আউটপুট
HashSet1-এ উপাদানসমূহ... 100 200 HashSet2-এ উপাদানসমূহ... 100 200 set1, set2-এর সাবসেট কি? True
দ্রষ্টব্য: HashSet ক্রম নিশ্চিত করে না। সেট অপারেশন (UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, IsSubsetOf, IsSupersetOf, Overlaps, SetEquals) সমর্থন করে।