C# में SortedSet<T> में अधिकतम मान प्राप्त करने के लिए, हम Max प्रॉपर्टी का उपयोग करते हैं। SortedSet तत्वों को स्वचालित रूप से क्रमबद्ध क्रम में बनाए रखता है, इसलिए अधिकतम तत्व हमेशा अंतिम तत्व होता है। इसी तरह Min प्रॉपर्टी न्यूनतम मान लौटाती है। यह System.Collections.Generic नेमस्पेस का हिस्सा है।
उदाहरण 1: स्ट्रिंग SortedSet में 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);
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);
}
}
आउटपुट
SortedSet1 में तत्व... AB BC CD EF SortedSet1 में अधिकतम तत्व = EF SortedSet2 में तत्व... (SortedSet के लिए एन्यूमरेटर) AB BC CD DE EF HI JK SortedSet2 में अधिकतम तत्व = JK
उदाहरण 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
मुख्य बिंदु:
MaxऔरMinप्रॉपर्टीज O(1) समय में अधिकतम/न्यूनतम तत्व लौटाती हैंSortedSetलाल-काले ट्री पर आधारित है - स्वचालित रूप से क्रमबद्ध रहता है- डुप्लिकेट तत्व स्वचालित रूप से अस्वीकृत किए जाते हैं
- यदि सेट खाली है, तो
Min/Maxएक्सेस करने परInvalidOperationExceptionफेंका जाता है - अंतिम तत्व =
Max, पहला तत्व =Min(क्रमबद्ध क्रम में) GetEnumerator()क्रमबद्ध क्रम में पुनरावृति करता हैReverse()उल्टे क्रम में एन्यूमरेटर लौटाता है