SortedDictionary<TKey, TValue> একটি সাজানো ডিকশনারি যা কী অনুযায়ী অর্ডার মেইনটেইন করে (লাল-কালো ট্রি বাস্তবায়ন)। ContainsKey() মেথড O(log n) সময়ে কী খুঁজে বের করে।
উদাহরণ ১: ইন্টিজার কী সহ SortedDictionary
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main() {
SortedDictionary sortedDict = new SortedDictionary();
sortedDict.Add(100, "Mobile");
sortedDict.Add(200, "Laptop");
sortedDict.Add(300, "Desktop");
sortedDict.Add(400, "Speakers");
sortedDict.Add(500, "Headphone");
sortedDict.Add(600, "Earphone");
Console.WriteLine("SortedDictionary কী-মান জোড়া...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("\nSortedDictionary-তে কী ২০০ আছে? = " + sortedDict.ContainsKey(200));
}
}
আউটপুট
SortedDictionary কী-মান জোড়া...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
SortedDictionary-তে কী ২০০ আছে? = True
উদাহরণ ২: স্ট্রিং কী সহ SortedDictionary
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main() {
SortedDictionary sortedDict = new SortedDictionary();
sortedDict.Add("A", "John");
sortedDict.Add("B", "Andy");
sortedDict.Add("C", "Tim");
sortedDict.Add("D", "Ryan");
sortedDict.Add("E", "Kevin");
sortedDict.Add("F", "Katie");
sortedDict.Add("G", "Brad");
Console.WriteLine("SortedDictionary কী-মান জোড়া...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("\nSortedDictionary-তে কী 'F' আছে? = " + sortedDict.ContainsKey("F"));
}
}
আউটপুট
SortedDictionary কী-মান জোড়া...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad
SortedDictionary-তে কী 'F' আছে? = True
তুলনা: SortedDictionary ইনসারশন/ডিলিশন O(log n), Dictionary O(1) এভারেজ। সাজানো অর্ডার দরকার হলে SortedDictionary ব্যবহার করুন।