परिचय
C# में SortedDictionary.Add() मेथड SortedDictionary<TKey, TValue> में निर्दिष्ट कुंजी और मान वाला एक तत्व जोड़ता है। कुंजी अद्वितीय होनी चाहिए।
सिंटैक्स
public void Add(TKey key, TValue value);
key जोड़े जाने वाले तत्व की कुंजी है, value तत्व का मान है।
उदाहरण 1: इंटीजर कुंजियों के साथ
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);
}
}
आउटपुट
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
उदाहरण 2: स्ट्रिंग कुंजियों के साथ
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("\nक्या SortedDictionary में कुंजी 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
महत्वपूर्ण बिंदु
- यदि कुंजी पहले से मौजूद है तो
ArgumentExceptionफेंकता है। - कुंजी
nullनहीं हो सकती (रेफरेंस टाइप्स के लिए)। - तत्व कुंजी के अनुसार सॉर्टेड क्रम में बने रहते हैं (बाइनरी सर्च ट्री)।
- समय जटिलता: O(log n)।
- मौजूदा कुंजी अपडेट करने या नई जोड़ने के लिए इंडेक्सर
dict[key] = valueका उपयोग करें (कोई अपवाद नहीं)। TryAdd()(.NET Core 2.0+) अपवाद के बिना जोड़ता है, सफलता दर्शाता है।