SortedSet in C#
DevSniper
191 Views
Namespace :- System.Collections.Generic
Assembly :- System.Collections.dll
Signature :-
public class SortedSet<T> :
System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlySet<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
- SortedSet does not store duplicate elements.
- SortedSet maintain ascending order of element that means elements in SortedSet stored in ascending order.
- You should use SortedSet if you required to store unique elements and maintain ascending order of elements.
- It can store user-defined objects also
- SortedSet is not thread safe.
SortedSet Constructors
- public SortedSet ();
- public SortedSet (System.Collections.Generic.IComparer<T>? comparer);
- public SortedSet (System.Collections.Generic.IEnumerable<T> collection);
- public SortedSet (System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T>? comparer);
SortedSet Properties
- Count :- public int Count { get; }
Gets the number of elements present in the sorted set.
- Comparer :- public System.Collections.Generic.IComparer<T> Comparer { get; }
Provide the IComparer<T> object which is used to order the values in the SortedSet.
- Max :- public T? Max { get; }
Get the maximum value form the Sorted set as defined by the comparer.
- Min :- public T? Min { get; }
Get the minimum value form the Sorted set as defined by the comparer.
Creating and adding element in a SortedSet
1. Using collection initializer
using System; using System.Collections.Generic; class Program { static void Main() { var set = new SortedSet<string>() { "C#", "Java", "C++", "Python", "React" }; foreach (var lang in set) { Console.WriteLine(lang); } } }
C# C++ Java Python React
2. Using Add Method
using System; using System.Collections.Generic; class Program { static void Main() { var set = new SortedSet<string>(); set.Add("Python"); set.Add("Java"); set.Add("C#"); set.Add("React"); set.Add("C++"); foreach (var lang in set) { Console.WriteLine(lang); } } }
C# C++ Java Python React