In this article, we will learn about the sets in C#.
A set is a collection that contains no duplicate elements.
There are two types of sets in C# under the System.Collections.Generic
namespace.
<ul><li>HashSet</li><li>SortedSet</li></ul>
HashSet does not store the elements in order while giving faster operation time.
SortedSet stores the elements in order which allows more functionality.
We create a HashSet / SortedSet in C# using the following syntax:
HashSet<T> l1 = new HashSet<T>();
SortedSet<T> l1 = new SortedSet<T>();
<T>
here denotes any datatype of which we want to create a list of.
Count
: This property gets the number of elements actually contained in the set.Comparer
: Determines equality for the values in the set.Max
: Gets the maximum value in the set, as defined by the comparer. (only for SortedSet)Min
: Gets the maximum value in the set, as defined by the comparer. (only for SortedSet)Add(T)
: Adds the element to the set.Clear()
: Removes all the elements from the set.Contains(T)
: Determines whether a value is in the set.Remove(T)
: Removes the element from the set.Different Set operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace SetDemo {
class Example {
static void Main(string[] args) {
HashSet < int > HS = new HashSet < int > ();
HS.Add(5);
HS.Add(5);
HS.Add(2);
HS.Add(9);
Console.WriteLine(HS.Count); // Prints 3 because 5 is only added once in the set
Console.WriteLine(HS.Contains(5)); // Checks if 5 is present
HS.Remove(5); // Removes 5
Console.WriteLine(HS.Contains(5)); // Prints False this time
SortedSet < int > SS = new SortedSet < int > ();
SS.Add(5);
SS.Add(5);
SS.Add(2);
SS.Add(9);
Console.WriteLine(SS.Max); // Prints the maximum element in the set
Console.WriteLine(SS.Min); // Prints the minimum element in the set
foreach(int i in SS) {
Console.Write(i + " ");
}
Console.WriteLine();
}
}
}
Output:
3
True
False
9
2
2 5 9
In the editor below, perform the different tasks as directed.