Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Collections and LINQ

Dictionaries, Sets and Queues

Learn VB.NET Dictionary(Of K, V), HashSet(Of T), Queue(Of T), Stack(Of T) and SortedDictionary - lookups, TryGetValue, set operations, FIFO and LIFO - with runnable C# stand-ins.

A list finds an item by scanning. When you need to ask "what is the price of product 42?" or "have I seen this word before?" thousands of times, scanning is too slow. .NET offers hash-based collections that answer in roughly constant time, plus queues and stacks for ordered processing. This lesson covers the ones you will use every week.

VB.NET is not runnable here, so VB is shown read-only and the examples you can run are C# stand-ins using the very same .NET types. Dictionary(Of String, Integer) in VB is Dictionary<string, int> in C#: same class, same behavior.

Dictionary(Of TKey, TValue)

A dictionary maps unique keys to values. Keys are hashed, so lookups, inserts and removals take about the same time whether it holds ten items or ten million.

VB
Dim stock As New Dictionary(Of String, Integer)
stock("apple") = 12            ' add or overwrite
stock.Add("pear", 4)           ' throws if the key already exists
Console.WriteLine(stock("apple"))

If stock.ContainsKey("kiwi") Then ...

Dim qty As Integer
If stock.TryGetValue("kiwi", qty) Then
    Console.WriteLine(qty)
Else
    Console.WriteLine("no kiwi")
End If

For Each pair In stock
    Console.WriteLine($"{pair.Key} = {pair.Value}")
Next

Reading a missing key with stock("kiwi") throws KeyNotFoundException, so use TryGetValue when absence is normal. Assigning with the indexer is an upsert; Add is strict. A key can be any type with sensible Equals and GetHashCode (strings, numbers, enums, structures, your own classes if you override both).

C# Counting words with a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Do not rely on the enumeration order of a plain Dictionary; it usually follows insertion order but is not guaranteed. If you need sorted keys use SortedDictionary(Of K, V) (a balanced tree, O(log n) operations) or sort the keys when you display them.

HashSet(Of T): unique values

A set stores each value once and answers Contains instantly. Adding a duplicate does nothing and returns False.

VB
Dim seen As New HashSet(Of Integer)
Dim isNew As Boolean = seen.Add(5)    ' True
isNew = seen.Add(5)                    ' False

Sets also provide the classic operations: UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, plus tests such as IsSubsetOf and Overlaps. They change the set they are called on.

C# Set operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Queue(Of T): first in, first out

A queue serves items in arrival order, like a line at a shop. Enqueue adds at the back, Dequeue removes from the front, Peek looks at the front without removing.

VB
Dim line As New Queue(Of String)
line.Enqueue("first")
line.Enqueue("second")
Console.WriteLine(line.Dequeue())   ' first

Use queues for job processing, breadth-first search, print spoolers and message buffers. Dequeue on an empty queue throws; check Count or use TryDequeue.

Stack(Of T): last in, first out

A stack hands back the most recently added item: Push, Pop, Peek. It models undo history, expression parsing and depth-first search.

C# Queue and Stack side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Which collection?

flowchart TD
    A["What do you need?"] --> B["Look up by key"]
    A --> C["Unique values only"]
    A --> D["Process in order"]
    B --> B1["Dictionary(Of K, V)"]
    C --> C1["HashSet(Of T)"]
    D --> D1["Queue (FIFO)"]
    D --> D2["Stack (LIFO)"]
    A --> E["Ordered, index access"]
    E --> E1["List(Of T)"]

Match the access pattern first, then pick the type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you read d("x") and the key is missing?

    The indexer throws for missing keys; TryGetValue avoids the exception.
  2. 2. What does HashSet(Of T).Add return when the value is already present?

    Add returns False and leaves the set unchanged.
  3. 3. Which structure gives first-in, first-out order?

    A queue dequeues in the order items were enqueued.
  4. 4. Which type keeps its keys sorted?

    SortedDictionary keeps keys in order using a balanced tree.

Summary

  • Dictionary(Of K, V) gives near-constant-time lookup by key; use TryGetValue for optional keys.
  • HashSet(Of T) stores unique values and supports union, intersection and difference.
  • Queue(Of T) is FIFO, Stack(Of T) is LIFO.
  • Use SortedDictionary when sorted key order matters.

Next: LINQ Basics