hashset vs dictionary c#

hashset vs dictionary c#


HashSet vs. Dictionary in C#

In C#, both HashSet<T> and Dictionary<TKey, TValue> are collections that use a hash-based implementation for storing data. While they have similarities in their use of hash codes for efficient data access, they serve different purposes. This article compares the two collections, exploring their differences, use cases, and practical examples.

Overview of HashSet and Dictionary

HashSet

A HashSet<T> is an unordered collection that stores unique elements. It excels in scenarios where only uniqueness and efficient lookups are required.

  • Unique Elements: Only one instance of any given value is stored.
  • No Key-Value Pairs: Works directly with individual values instead of key-value pairs.
  • High Performance: Fast membership testing with O(1) complexity.

Dictionary

A Dictionary<TKey, TValue> is a key-value pair collection optimized for efficient retrieval.

  • Key-Value Pair: Each key maps uniquely to a value.
  • Unique Keys: Keys must be unique, but values can be duplicated.
  • Indexed Access: Allows fast value retrieval based on the key.

Key Differences

Data Structure

  • HashSet: Stores single values directly without a key.
  • Dictionary: Uses key-value pairs where each key maps to a specific value.

Membership Testing

  • HashSet: Contains quickly checks whether an element is present.
  • Dictionary: ContainsKey checks for keys, while ContainsValue searches values.

Access Complexity

  • HashSet: Offers efficient O(1) membership testing.
  • Dictionary: Provides O(1) access by key but can be slower for searching values.

Practical Examples

HashSet Example

 

using System;
using System.Collections.Generic;

public class HashSetExample
{
    public static void Main()
    {
        // Creating a HashSet of integers
        HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5 };

        // Adding and checking for unique numbers
        bool isAdded = numbers.Add(6);
        Console.WriteLine($"Was 6 added to HashSet? {isAdded}");

        bool containsFour = numbers.Contains(4);
        Console.WriteLine($"Does HashSet contain 4? {containsFour}");
    }
}

Dictionary Example

 

using System;
using System.Collections.Generic;

public class DictionaryExample
{
    public static void Main()
    {
        // Creating a Dictionary with string keys and integer values
        Dictionary<string, int> scores = new Dictionary<string, int>
        {
            { "Alice", 90 },
            { "Bob", 85 },
            { "Charlie", 95 }
        };

        // Adding a new key-value pair
        scores["Dave"] = 88;

        // Accessing a value by key
        int bobScore = scores["Bob"];
        Console.WriteLine($"Bob's score: {bobScore}");

        // Checking if a key exists
        bool hasAlice = scores.ContainsKey("Alice");
        Console.WriteLine($"Is Alice in the dictionary? {hasAlice}");
    }
}

Choosing Between HashSet and Dictionary

Choose HashSet if:

  • You need a unique collection of elements.
  • Fast membership testing is crucial.
  • Key-value pairs are not required.

Choose Dictionary if:

  • You need to map unique keys to specific values.
  • Fast access by a unique identifier is essential.
  • You require direct indexed access via keys.

Conclusion

HashSet<T> and Dictionary<TKey, TValue> are both powerful collections with specific use cases in C#. By understanding their differences and practical applications, you can choose the right collection to optimize data handling in your application.


 

Leave a reply Your email address will not be published. Required fields are marked*