C# में SortedList में निहित तत्वों (कुंजी-मान जोड़े) की संख्या प्राप्त करने के लिए, हम Count प्रॉपर्टी का उपयोग करते हैं। SortedList कुंजी-मान जोड़े का एक संग्रह है जो कुंजियों के आधार पर स्वचालित रूप से क्रमबद्ध होता है। यह System.Collections नेमस्पेस में स्थित एक गैर-जेनेरिक संग्रह है।
उदाहरण 1: SortedList गिनना और साफ़ करना
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList sortedList = new SortedList();
sortedList.Add("A", "1");
sortedList.Add("B", "2");
sortedList.Add("C", "3");
sortedList.Add("D", "4");
sortedList.Add("E", "5");
sortedList.Add("F", "6");
sortedList.Add("G", "7");
sortedList.Add("H", "8");
sortedList.Add("I", "9");
sortedList.Add("J", "10");
Console.WriteLine("SortedList तत्व...");
foreach (DictionaryEntry d in sortedList)
{
Console.WriteLine("कुंजी = " + d.Key + ", मान = " + d.Value);
}
Console.WriteLine("SortedList कुंजी-मान जोड़े की संख्या = " + sortedList.Count);
sortedList.Clear();
Console.WriteLine("SortedList की संख्या (अपडेटेड) = " + sortedList.Count);
}
}
आउटपुट
SortedList तत्व... कुंजी = A, मान = 1 कुंजी = B, मान = 2 कुंजी = C, मान = 3 कुंजी = D, मान = 4 कुंजी = E, मान = 5 कुंजी = F, मान = 6 कुंजी = G, मान = 7 कुंजी = H, मान = 8 कुंजी = I, मान = 9 कुंजी = J, मान = 10 SortedList कुंजी-मान जोड़े की संख्या = 10 SortedList की संख्या (अपडेटेड) = 0
उदाहरण 2: एन्यूमरेटर के साथ SortedList गिनती
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList sortedList = new SortedList();
sortedList.Add("One", "1");
sortedList.Add("Two", "2");
sortedList.Add("Three", "3");
sortedList.Add("Four", "4");
sortedList.Add("Five", "5");
sortedList.Add("Six", "6");
sortedList.Add("Seven", "7");
sortedList.Add("Eight", "8");
sortedList.Add("Nine", "9");
sortedList.Add("Ten", "10");
Console.WriteLine("SortedList कुंजी-मान जोड़े की संख्या = " + sortedList.Count);
Console.WriteLine("SortedList के माध्यम से पुनरावृति करने वाला एन्यूमरेटर...");
IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("कुंजी = " + demoEnum.Key + ", मान = " + demoEnum.Value);
}
}
आउटपुट
SortedList कुंजी-मान जोड़े की संख्या = 10 SortedList के माध्यम से पुनरावृति करने वाला एन्यूमरेटर... कुंजी = Eight, मान = 8 कुंजी = Five, मान = 5 कुंजी = Four, मान = 4 कुंजी = Nine, मान = 9 कुंजी = One, मान = 1 कुंजी = Seven, मान = 7 कुंजी = Six, मान = 6 कुंजी = Ten, मान = 10 कुंजी = Three, मान = 3 कुंजी = Two, मान = 2
मुख्य बिंदु:
Countप्रॉपर्टी O(1) समय में कुंजी-मान जोड़े की संख्या लौटाती है- तत्व कुंजियों के आधार पर स्वचालित रूप से क्रमबद्ध होते हैं
Clear()सभी तत्वों को हटा देता हैIDictionaryEnumeratorक्रमबद्ध क्रम में पुनरावृति करता है- कुंजियाँ अद्वितीय होनी चाहिए - डुप्लिकेट कुंजी पर अपवाद फेंका जाता है
- आधुनिक C# में
SortedList<TKey, TValue>(जेनेरिक) याSortedDictionary<TKey, TValue>का उपयोग करें