C# में SortedList ऑब्जेक्ट में सभी कुंजियाँ प्राप्त करने के लिए, हम Keys प्रॉपर्टी का उपयोग करते हैं जो एक ICollection लौटाती है। SortedList कुंजी-मान जोड़े को कुंजियों के आधार पर स्वचालित रूप से क्रमबद्ध रखता है। यह System.Collections नेमस्पेस में स्थित एक गैर-जेनेरिक संग्रह है।
उदाहरण 1: कुंजियों का संग्रह प्राप्त करना और इंडेक्स जांचना
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList list = new SortedList();
list.Add("One", "Finance");
list.Add("Two", "Marketing");
list.Add("Three", "Sales");
list.Add("Four", "Purchase");
list.Add("Five", "Operations");
list.Add("Six", "IT");
Console.WriteLine("SortedList तत्व...");
foreach (DictionaryEntry d in list)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nकुंजी One पर इंडेक्स = " + list.IndexOfKey("One"));
ICollection col = list.Keys;
Console.WriteLine("\nकुंजियों का संग्रह...");
foreach (string res in col)
Console.WriteLine(res);
}
}
आउटपुट
SortedList तत्व... Five Operations Four Purchase One Finance Six IT Three Sales Two Marketing कुंजी One पर इंडेक्स = 2 कुंजियों का संग्रह... Five Four One Six Three Two
उदाहरण 2: दो SortedList ऑब्जेक्ट्स की कुंजियाँ
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two", 2);
list1.Add("Three", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven", 7);
list1.Add("Eight", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 तत्व...");
foreach (DictionaryEntry d in list1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
ICollection col = list1.Keys;
Console.WriteLine("\nList1 में कुंजियों का संग्रह...");
foreach (string res in col)
Console.WriteLine(res);
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nSortedList2 तत्व...");
foreach (DictionaryEntry d in list2)
{
Console.WriteLine(d.Key + " " + d.Value);
}
col = list2.Keys;
Console.WriteLine("\nList2 में कुंजियों का संग्रह...");
foreach (string res in col)
Console.WriteLine(res);
}
}
आउटपुट
SortedList1 तत्व... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 List1 में कुंजियों का संग्रह... Eight Five Four Nine One Seven Six Ten Three Two SortedList2 तत्व... A Accessories B Books C Smart Wearable Tech D Home Appliances List2 में कुंजियों का संग्रह... A B C D
मुख्य बिंदु:
Keysप्रॉपर्टी क्रमबद्ध क्रम में कुंजियों का संग्रह लौटाती हैIndexOfKey()कुंजी का शून्य-आधारित इंडेक्स लौटाता है- कुंजियाँ क्रमबद्ध क्रम में संग्रहीत होती हैं (स्ट्रिंग्स के लिए वर्णानुक्रमिक)
Valuesप्रॉपर्टी मानों का संग्रह लौटाती है- आधुनिक C# में
SortedDictionary<TKey, TValue>याSortedList<TKey, TValue>(जेनेरिक) का उपयोग करें