SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet.Add(T) Method is used to add an element to the set and returns a value that specify if it was successfully added or not.
Properties:
- In C#, SortedSet class can be used to store, remove or view elements.
- It maintains ascending order and does not store duplicate elements.
- It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order.
Syntax:
public bool Add (T item);
Parameter:
item: The element which is added to the set.
Return Value: True if item is added to the set, otherwise False.
Example 1:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
SortedSet< int > mySortedSet = new SortedSet< int >();
for ( int i = 2; i < 7; i++) {
mySortedSet.Add(i * 2);
}
foreach ( int i in mySortedSet)
{
Console.WriteLine(i);
}
}
}
|
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
SortedSet< int > mySortedSet = new SortedSet< int >();
mySortedSet.Add(4);
mySortedSet.Add(5);
mySortedSet.Add(6);
mySortedSet.Add(6);
mySortedSet.Add(6);
mySortedSet.Add(6);
mySortedSet.Add(7);
foreach ( int i in mySortedSet)
{
Console.WriteLine(i);
}
}
}
|
Reference: