Dictionary and HashSet equality
Dictionary and HashSet equality
Use a dictionary to associate unique keys with values and a hash set to track membership. An equality comparer defines which keys or members represent the same identity.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; outputs are predictions pending compilation.
Define identity before storing values
For machine identifiers, ordinal comparison is usually appropriate; choose case sensitivity according to the domain. StringComparer.OrdinalIgnoreCase treats letter casing as irrelevant using ordinal rules rather than a user language. A comparer supplies equality and a compatible hash code. Equal values must have equal hashes; equal hashes need not mean equal values.
using System;using System.Collections.Generic;var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);foreach (string code in new[] { "A1", "a1", "B2" }){ counts.TryGetValue(code, out int previous); counts[code] = previous + 1;}Console.WriteLine(counts.Count);Console.WriteLine(counts["a1"]);Console.WriteLine(counts.TryGetValue("C3", out _));The comparer merges A1 and a1. For int values, a missing lookup sets the out value to zero; its Boolean result distinguishes absence from a stored zero.
Expected output (reasoned, not executed):
22FalseHandle duplicate insertion explicitly
Dictionary.Add rejects an existing key with ArgumentException. TryAdd returns false instead; assigning through the indexer replaces an existing value or creates a new entry. Reading a missing indexer key throws KeyNotFoundException. Use TryGetValue for expected absence. HashSet.Add returns a Boolean indicating whether membership changed.
using System;using System.Collections.Generic;var checkedIn = new HashSet<string>(StringComparer.OrdinalIgnoreCase);Console.WriteLine(checkedIn.Add("Desk-1"));Console.WriteLine(checkedIn.Add("desk-1"));Console.WriteLine(checkedIn.Contains("DESK-1"));Console.WriteLine(checkedIn.Count);The second addition is not a new identity, regardless of spelling. No iteration order is assumed.
Expected output (reasoned, not executed):
TrueFalseTrue1Choose stable keys and set operations
Changing a field used by a key’s equality or hash code while the key is stored can make lookup unreliable. Use immutable identity data such as a string, int or record with stable equality components. Hash tables generally provide efficient average-case lookup, not a universal constant-time guarantee. Set operations include UnionWith, IntersectWith, ExceptWith and SetEquals; several mutate the receiver.
using System;using System.Collections.Generic;var required = new HashSet<int> { 10, 20, 30 };var scanned = new HashSet<int> { 20, 30, 30 };required.ExceptWith(scanned);Console.WriteLine(required.Count);Console.WriteLine(required.Contains(10));Console.WriteLine(scanned.SetEquals(new[] { 30, 20 }));ExceptWith leaves only the missing ID in required. SetEquals ignores order and repeated values in its input.
Expected output (reasoned, not executed):
1TrueTrueCommon mistakes and edge cases
Never infer equality solely from hash codes. Avoid using mutable keys whose equality changes. Do not silently overwrite a duplicate when the domain requires rejecting it. Distinguish an absent key from a valid zero value.
Practice and next steps
Count identifiers ["R1","r1","R2","r1"] with an ordinal case-insensitive dictionary, and report missing R3 using TryGetValue. Build a set of those same identifiers; then remove R2. Explain the count at each stage.
Next: Queue, Stack and priority queue.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dictionary and HashSet equality — knowledge check
Apply the lesson concepts to the following scenarios.
What does HashSet.Add return for an already present equal item?
How should equal keys behave under a custom hash comparer?
Which dictionary operation reports duplicate insertion without replacing a value?
A lookup returns false and sets an int out parameter to zero. What does it mean?
Which method checks membership equality without requiring the same order?