HashSet<T> Class

Namespace: System.Collections.Generic

Overview

Represents a collection of objects that are unordered, unique, and can be accessed by hash. A <see cref="T:System.Collections.Generic.HashSet`1"> collection is a set that contains no duplicate elements.

This collection uses a hash table to store elements, which provides excellent performance for adding, removing, and checking for the existence of elements. The average time complexity for these operations is O(1).

Key Characteristics:

Syntax


public class HashSet<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, IReadOnlyCollection<T>
            

Namespace: System.Collections.Generic
Assembly: System.Collections.dll

Constructors

Methods

Example Usage


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a HashSet of strings
        HashSet<string> fruits = new HashSet<string>();

        // Add elements
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Orange");

        // Adding a duplicate will return false and not add the element
        bool addedGrape = fruits.Add("Grape");
        bool addedAppleAgain = fruits.Add("Apple"); // This will be false

        Console.WriteLine($"'Grape' added: {addedGrape}"); // Output: 'Grape' added: True
        Console.WriteLine($"'Apple' added again: {addedAppleAgain}"); // Output: 'Apple' added again: False

        // Check if an element exists
        bool hasBanana = fruits.Contains("Banana");
        Console.WriteLine($"Contains 'Banana': {hasBanana}"); // Output: Contains 'Banana': True

        // Iterate through the set
        Console.WriteLine("Fruits in the set:");
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        // Remove an element
        bool removedOrange = fruits.Remove("Orange");
        Console.WriteLine($"'Orange' removed: {removedOrange}"); // Output: 'Orange' removed: True

        Console.WriteLine($"Number of fruits: {fruits.Count}"); // Output: Number of fruits: 3

        // Set operations
        HashSet<string> moreFruits = new HashSet<string> { "Apple", "Mango", "Pineapple" };

        fruits.UnionWith(moreFruits); // Union: { "Apple", "Banana", "Grape", "Mango", "Pineapple" }
        Console.WriteLine($"\nAfter UnionWith: {string.Join(", ", fruits)}");

        fruits.IntersectWith(moreFruits); // Intersection: { "Apple" }
        Console.WriteLine($"After IntersectWith: {string.Join(", ", fruits)}");
    }
}
            

Related Topics