0
0
CsharpComparisonBeginner · 3 min read

HashSet vs List in C#: Key Differences and When to Use Each

In C#, HashSet is a collection that stores unique elements with fast lookup and no guaranteed order, while List allows duplicates, maintains insertion order, and supports indexed access. Use HashSet when you need quick membership tests and uniqueness, and List when order and duplicates matter.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of HashSet and List in C# based on key factors.

FactorHashSetList
Duplicates AllowedNo, only unique elementsYes, duplicates allowed
Order MaintainedNo guaranteed orderYes, maintains insertion order
Lookup SpeedFast (O(1) average)Slower (O(n))
Index AccessNo index accessSupports index access
Use CaseFast membership and uniquenessOrdered collection with duplicates
Memory UsageHigher due to hashingLower compared to HashSet
⚖️

Key Differences

HashSet is designed to store unique elements only. It uses a hash-based structure internally, which allows very fast checks to see if an item exists. This makes it ideal when you want to avoid duplicates and quickly test membership. However, it does not keep elements in any particular order, so you cannot rely on the order of items when iterating.

On the other hand, List is a simple ordered collection that allows duplicates. It stores elements in the order they were added and supports accessing elements by their index. Lookup operations like checking if an item exists are slower because it may need to scan through the list. Lists use less memory than hash sets because they don't store extra data for hashing.

In summary, HashSet is best when uniqueness and fast lookup are priorities, while List is better when order and duplicates matter or when you need to access elements by position.

⚖️

Code Comparison

Here is an example showing how to add elements and check for existence using a HashSet in C#.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<string> fruits = new HashSet<string>();
        fruits.Add("apple");
        fruits.Add("banana");
        fruits.Add("apple"); // Duplicate ignored

        Console.WriteLine("Fruits in HashSet:");
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("Contains 'banana'? " + fruits.Contains("banana"));
    }
}
Output
Fruits in HashSet: apple banana Contains 'banana'? True
↔️

List Equivalent

Here is the equivalent example using a List in C# to add elements and check for existence.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string>();
        fruits.Add("apple");
        fruits.Add("banana");
        fruits.Add("apple"); // Duplicate allowed

        Console.WriteLine("Fruits in List:");
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("Contains 'banana'? " + fruits.Contains("banana"));
    }
}
Output
Fruits in List: apple banana apple Contains 'banana'? True
🎯

When to Use Which

Choose HashSet when you need to store unique items and perform fast membership checks without caring about order. It is perfect for scenarios like removing duplicates or quickly testing if an item exists.

Choose List when you need to preserve the order of elements, allow duplicates, or access items by their position. Lists are better for ordered collections, queues, or when you want to keep all entries including duplicates.

In short, use HashSet for uniqueness and speed, and List for order and duplicates.

Key Takeaways

Use HashSet for unique elements and fast lookup without order.
Use List when order matters and duplicates are allowed.
HashSet has faster membership tests but no index access.
List supports duplicates and indexed access but slower lookups.
Choose based on whether uniqueness or order is more important.