0
0
C Sharp (C#)programming~5 mins

HashSet for unique elements in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A HashSet helps you keep a collection of items where each item appears only once. It automatically ignores duplicates.

When you want to store a list of unique names without repeats.
When you need to check quickly if an item is already in a collection.
When you want to remove duplicate values from a list.
When you want to combine two lists but keep only unique items.
When you want to count how many different items you have.
Syntax
C Sharp (C#)
HashSet<T> set = new HashSet<T>();

// Add items
set.Add(item);

// Check if item exists
bool hasItem = set.Contains(item);

// Remove item
set.Remove(item);

T is the type of items you want to store, like int or string.

HashSet does not keep items in order.

Examples
This creates a set of fruits and adds "apple" and "banana". The second "apple" is ignored because it is a duplicate.
C Sharp (C#)
HashSet<string> fruits = new HashSet<string>();
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("apple"); // duplicate ignored
You can initialize a HashSet with values. Duplicates like the second 2 are ignored.
C Sharp (C#)
HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 2 };
// The set will contain 1, 2, 3 only once each
Check if "banana" is in the set and print a message.
C Sharp (C#)
if (fruits.Contains("banana")) {
    Console.WriteLine("Banana is in the set.");
}
Sample Program

This program creates a HashSet of colors, adds some colors including a duplicate, and shows how duplicates are ignored. It also checks if a color exists and removes one.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        HashSet<string> colors = new HashSet<string>();
        colors.Add("red");
        colors.Add("blue");
        colors.Add("green");
        colors.Add("red"); // duplicate ignored

        Console.WriteLine("Colors in the set:");
        foreach (var color in colors) {
            Console.WriteLine(color);
        }

        Console.WriteLine($"Contains 'blue'? {colors.Contains("blue")}");
        colors.Remove("green");
        Console.WriteLine("After removing 'green':");
        foreach (var color in colors) {
            Console.WriteLine(color);
        }
    }
}
OutputSuccess
Important Notes

HashSet is very fast for checking if an item exists.

Order of items in HashSet is not guaranteed.

Use HashSet when you want only unique items without caring about order.

Summary

HashSet stores unique items and ignores duplicates automatically.

It is useful for fast lookups and removing duplicates.

Items in a HashSet are not stored in any particular order.