C# में SortedSet<T> में न्यूनतम मान प्राप्त करने के लिए, हम Min प्रॉपर्टी का उपयोग करते हैं। SortedSet तत्वों को स्वचालित रूप से क्रमबद्ध क्रम में बनाए रखता है, इसलिए न्यूनतम तत्व हमेशा पहला तत्व होता है। इसी तरह Max प्रॉपर्टी अधिकतम मान लौटाती है। यह System.Collections.Generic नेमस्पेस का हिस्सा है।
उदाहरण 1: स्ट्रिंग SortedSet में Min और Max
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);
}
Console.WriteLine("SortedSet1 में अधिकतम तत्व = " + set1.Max);
Console.WriteLine("SortedSet1 में न्यूनतम तत्व = " + set1.Min);
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);
}
Console.WriteLine("SortedSet2 में अधिकतम तत्व = " + set2.Max);
Console.WriteLine("SortedSet2 में न्यूनतम तत्व = " + set2.Min);
}
}
आउटपुट
SortedSet1 में तत्व... AB BC CD EF SortedSet1 में अधिकतम तत्व = EF SortedSet1 में न्यूनतम तत्व = AB SortedSet2 में तत्व... (SortedSet के लिए एन्यूमरेटर) AB BC CD DE EF HI JK SortedSet2 में अधिकतम तत्व = JK SortedSet2 में न्यूनतम तत्व = AB
उदाहरण 2: पूर्णांक SortedSet में Min और Max
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(5);
set1.Add(50);
set1.Add(20);
set1.Add(10);
set1.Add(70);
set1.Add(60);
set1.Add(55);
set1.Add(95);
Console.WriteLine("SortedSet में तत्व...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet में अधिकतम तत्व = " + set1.Max);
Console.WriteLine("SortedSet में न्यूनतम तत्व = " + set1.Min);
}
}
आउटपुट
SortedSet में तत्व... 5 10 20 50 55 60 70 95 SortedSet में अधिकतम तत्व = 95 SortedSet में न्यूनतम तत्व = 5
मुख्य बिंदु:
MinऔरMaxप्रॉपर्टीज O(1) समय में न्यूनतम/अधिकतम तत्व लौटाती हैंSortedSetलाल-काले ट्री पर आधारित है - स्वचालित रूप से क्रमबद्ध रहता है- डुप्लिकेट तत्व स्वचालित रूप से अस्वीकृत किए जाते हैं
- यदि सेट खाली है, तो
Min/Maxएक्सेस करने परInvalidOperationExceptionफेंका जाता है - पहला तत्व =
Min, अंतिम तत्व =Max(क्रमबद्ध क्रम में) GetEnumerator()क्रमबद्ध क्रम में पुनरावृति करता है