![]() |
VOOZH | about |
SortedSet<T> is a collection of unique elements that are automatically sorted in ascending order by default. It is implemented using a balanced binary search tree (red-black tree), which provides efficient insertion, deletion and search operations. There are some key features mentioned below:
using System.Collections.Generic;
SortedSet<type_of_sortedset> sortedset_name = new SortedSet<type_of_sortedset>();
Example:
SortedSet elements: 1 2 4 6 7 8
Note: Duplicate elements are automatically ignored.
// Using the Add() method
SortedSet<int> num= new SortedSet<int>();
num.Add(1);
num.Add(2);// Using Collection Initalizer
SortedSet<int> num = new SortedSet<int> { 2, 1, 4,3 };
Using foreach loop: We can use foreach loop to iterate each element to access the sorted set.
SortedSet<int> numbers= new SortedSet<int> { 2,3,4,5};
foreach (int num in numbers)
Console.WriteLine(num);
Using ForEach loop with Lambda Expressions: Lambda expressions reduces the number of code lines and enhances the code readability.
SortedSet<int> numbers = new SortedSet<int> { 2, 3, 4, 5 };
numbers.ToList().ForEach(n => Console.WriteLine(n));
Using ElementAt() with LINQ: The SortedSet does not directly support indexing but we can use LINQ and use ElementAt() method.
using System.Linq;
SortedSet<int> numbers= new SortedSet<int> { 2,3,4,5 };
Console.WriteLine(numbers.ElementAt(0));
Example: Accessing Elements Using Different Methods
Accessing using foreach loop: 2 3 4 5 Accessing using ForEach loop: 1 2 3
SortedSet<T> provides three ways to remove elements:
Example:
Total number of elements present in set: 4 Total number of elements present in set after Remove(1): 3 Total number of elements present in set after Clear(): 0
We can check the presence of a specific element using the Contains method. Example:
Element is available.