C# में SortedSet<T> बनाने के लिए, हम इसके कंस्ट्रक्टर का उपयोग करते हैं और फिर Add() मेथड से तत्व जोड़ते हैं। SortedSet एक ऐसा संग्रह है जो अद्वितीय तत्वों को क्रमबद्ध क्रम में बनाए रखता है। यह System.Collections.Generic नेमस्पेस का हिस्सा है और लाल-काले ट्री (self-balancing BST) पर आधारित है।
उदाहरण 1: दो SortedSet बनाना और एन्यूमरेटर से पुनरावृति
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<string> set1 = new SortedSet<string>();
set1.Add("AB");
set1.Add("BC");
set1.Add("CD");
set1.Add("EF");
Console.WriteLine("SortedSet1 में तत्व...");
foreach (string res in set1)
{
Console.WriteLine(res);
}
SortedSet<string> set2 = new SortedSet<string>();
set2.Add("BC");
set2.Add("CD");
set2.Add("DE");
set2.Add("EF");
set2.Add("AB");
set2.Add("HI");
set2.Add("JK");
Console.WriteLine("SortedSet2 में तत्व... (SortedSet के लिए एन्यूमरेटर)");
SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
}
}
आउटपुट
SortedSet1 में तत्व... AB BC CD EF SortedSet2 में तत्व... (SortedSet के लिए एन्यूमरेटर) AB BC CD DE EF HI JK
उदाहरण 2: शर्त-आधारित निष्कासन के साथ SortedSet
using System;
using System.Collections.Generic;
public class Demo
{
private static bool Demo(int i)
{
return ((i % 10) == 0);
}
public static void Main(String[] args)
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(200);
set1.Add(215);
set1.Add(310);
set1.Add(500);
set1.Add(600);
Console.WriteLine("SortedSet तत्व...");
foreach (int i in set1)
{
Console.WriteLine(i);
}
Console.WriteLine(" ");
set1.RemoveWhere(Demo); // 10 से विभाज्य तत्व हटाएं
Console.WriteLine("कुछ तत्व हटाने के बाद SortedSet...");
foreach (int i in set1)
{
Console.WriteLine(i);
}
}
}
आउटपुट
SortedSet तत्व... 200 215 310 500 600 SortedSet कुछ तत्व हटाने के बाद... 215
मुख्य बिंदु:
SortedSetतत्वों को स्वचालित रूप से क्रमबद्ध क्रम में रखता है- डुप्लिकेट मान स्वचालित रूप से अस्वीकृत कर दिए जाते हैं
GetEnumerator()क्रमबद्ध क्रम में पुनरावृति करने वाला एन्यूमरेटर लौटाता हैRemoveWhere()प्रीडिकेट के आधार पर तत्व हटाता है- सेट ऑपरेशंस:
UnionWith(),IntersectWith(),ExceptWith(),IsSubsetOf(),IsSupersetOf() - O(log n) इंसर्शन, डिलीशन, और लुकअप