Home > Article > Backend Development > SortedSet class in C#
The SortedSet class in C# represents a collection of objects that is maintained in sorted order.
Following are the properties of the SortedSet class −
Sr.No | Property & Description |
---|---|
Comparer Gets the IComparer8742468051c85b06f0a0af9e3e506b5c object that is used to order the values in the SortedSet8742468051c85b06f0a0af9e3e506b5c. | |
CountGets the number of elements in the SortedSet8742468051c85b06f0a0af9e3e506b5c. | |
MaxGets the maximum value in the SortedSet8742468051c85b06f0a0af9e3e506b5c, as defined by the comparer. | |
MinGets the minimum value in the SortedSet< ;T>, as Defined by the comparator. |
Method and Description | |
---|---|
Add(T) | Add elements to the collection , and returns a value indicating whether the element was successfully added. |
2
##3
##6
CreateSetComparer()
Examples
Now let’s see some examples −
using System; using System.Collections.Generic; public class Demo { public static void Main() { SortedSet<string> set1 = new SortedSet<string>(); set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); Console.WriteLine("Elements in SortedSet1..."); foreach (string res in set1) { Console.WriteLine(res); } Console.WriteLine("Does the SortedSet1 contains the element DE? = "+set1.Contains("DE")); 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("Elements in SortedSet2..."); foreach (string res in set2) { Console.WriteLine(res); } Console.WriteLine("SortedSet2 is a superset of SortedSet1? = "+set2.IsSupersetOf(set1)); } }
Elements in SortedSet1... CD Does the SortedSet1 contains the element DE? = False Elements in SortedSet2... AB BC CD DE EF HI JK SortedSet2 is a superset of SortedSet1? = TrueTo obtain an enumerator that traverses SortedSet, the code is as follows −Example Online Demonstration
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("Elements in 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("Elements in SortedSet2 (Enumerator for SortedSet)..."); SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator(); while (demoEnum.MoveNext()) { string res = demoEnum.Current; Console.WriteLine(res); } } }OutputThis will produce the following output −
Elements in SortedSet1... AB BC CD EF Elements in SortedSet2 (Enumerator for SortedSet)... AB BC CD DE EF HI JK
The above is the detailed content of SortedSet class in C#. For more information, please follow other related articles on the PHP Chinese website!