LogIn
I don't have account.

HashSet in C#

DevSniper
131 Views

Namespace :- System.Collections.Generic

Assembly :- System.Collections.dll

Signature :-
public class HashSet<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.Runtime.Serialization.IDeserializationCallback,
   System.Runtime.Serialization.ISerializable
  • HashSet provides constant time complexity O(1) for basic operations like add, remove and contains.
  • HashSet does not store duplicate elements. if you add duplicate values in the set, only one instance of that value will be available other will be discarded.
  • HashSet support set operations like union , intersection and difference. These operations are useful in scenarios such as to finding common element within sets or combining multiple sets
  • HashSet can store user-defined objects also
  • HashSet does not maintain order of element it uses hashing mechanism to store data for faster lookup
  • HashSet is not inherently thread-safe from multiple threads.
HashSet Constructors
  1. public HashSet ();
  2. public HashSet (System.Collections.Generic.IEnumerable<T> collection);
  3. public HashSet (System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T>? comparer);
  4. public HashSet (System.Collections.Generic.IEqualityComparer<T>? comparer);
  5. public HashSet (int capacity);
  6. public HashSet (int capacity, System.Collections.Generic.IEqualityComparer<T>? comparer);
HashSet Properties
  • Count :- public int Count { get; }

    Gets the number of elements present in the set.

  • Comparer :- public System.Collections.Generic.IEqualityComparer<T> Comparer { get; }

    Gets the IEqualityComparer<T> object which is used to determine equality between the values in the set.

Creating and adding element in a HashSet
1. Using Collection initializer.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var set = new HashSet<string>() { "C#", "Java", "C++", "Python", "React" };
        foreach (var lang in set) {
            Console.WriteLine(lang);
        }
    }
}
2. using Add method
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var set = new HashSet<string>();
        set.Add("C#");
        set.Add("C++");
        set.Add("Python");
        set.Add("Java");
        set.Add("React");
        foreach (var lang in set) {
            Console.WriteLine(lang);
        }
    }
}