C# में SortedDictionary<TKey, TValue> में कोई निर्दिष्ट कुंजी मौजूद है या नहीं यह जांचने के लिए, हम ContainsKey() मेथड का उपयोग करते हैं। SortedDictionary एक बाइनरी सर्च ट्री पर आधारित डिक्शनरी है जो कुंजियों के आधार पर क्रमबद्ध क्रम में तत्वों को बनाए रखती है। यह System.Collections.Generic नेमस्पेस का हिस्सा है।
उदाहरण 1: पूर्णांक कुंजियों के साथ SortedDictionary
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
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("कुंजी = " + demoEnum.Key + ", मान = " + demoEnum.Value);
Console.WriteLine("\nक्या SortedDictionary में कुंजी 200 है? = " + sortedDict.ContainsKey(200));
}
}
आउटपुट
SortedDictionary कुंजी-मान जोड़े... कुंजी = 100, मान = Mobile कुंजी = 200, मान = Laptop कुंजी = 300, मान = Desktop कुंजी = 400, मान = Speakers कुंजी = 500, मान = Headphone कुंजी = 600, मान = Earphone क्या SortedDictionary में कुंजी 200 है? = True
उदाहरण 2: स्ट्रिंग कुंजियों के साथ SortedDictionary
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
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("कुंजी = " + demoEnum.Key + ", मान = " + demoEnum.Value);
Console.WriteLine("\nक्या SortedDictionary में कुंजी F है? = " + sortedDict.ContainsKey("F"));
}
}
आउटपुट
SortedDictionary कुंजी-मान जोड़े... कुंजी = A, मान = John कुंजी = B, मान = Andy कुंजी = C, मान = Tim कुंजी = D, मान = Ryan कुंजी = E, मान = Kevin कुंजी = F, मान = Katie कुंजी = G, मान = Brad क्या SortedDictionary में कुंजी F है? = True
मुख्य बिंदु:
ContainsKey()O(log n) समय में कुंजी की उपस्थिति जांचता है (बाइनरी सर्च ट्री)- तत्व कुंजियों के आधार पर स्वचालित रूप से क्रमबद्ध रहते हैं
- कुंजियाँ अद्वितीय होनी चाहिए - डुप्लिकेट कुंजी जोड़ने पर अपवाद फेंका जाता है
IDictionaryEnumeratorक्रमबद्ध क्रम में पुनरावृति करता है- संबंधित मेथड्स:
ContainsValue(),TryGetValue()