What is the best way to iterate over a Dictionary in C#?

A Dictionary is a collection of key-value pairs in C#. The Dictionary<TKey, TValue> class is included in the System.Collections.Generic namespace and provides several efficient ways to iterate through its elements.

There are multiple approaches to iterate over a Dictionary, each with its own advantages depending on whether you need keys, values, or both.

Syntax

Following are the common syntaxes for iterating over a Dictionary −

// Using foreach with KeyValuePair
foreach (KeyValuePair<TKey, TValue> item in dictionary) {
   // Access item.Key and item.Value
}

// Using foreach with var
foreach (var item in dictionary) {
   // Access item.Key and item.Value
}

// Iterating over Keys only
foreach (var key in dictionary.Keys) {
   // Access dictionary[key] for value
}

// Iterating over Values only
foreach (var value in dictionary.Values) {
   // Access value directly
}

Using foreach with KeyValuePair

The most common and recommended way is to use foreach with KeyValuePair to access both keys and values −

using System;
using System.Collections.Generic;

class Program {
   public static void Main() {
      var vehicles = new Dictionary<string, int>();
      
      // Add key-value pairs
      vehicles.Add("car", 25);
      vehicles.Add("bus", 28);
      vehicles.Add("motorbike", 17);
      vehicles.Add("truck", 32);
      
      Console.WriteLine("Vehicle speeds:");
      foreach (KeyValuePair<string, int> vehicle in vehicles) {
         Console.WriteLine("{0} = {1} mph", vehicle.Key, vehicle.Value);
      }
   }
}

The output of the above code is −

Vehicle speeds:
car = 25 mph
bus = 28 mph
motorbike = 17 mph
truck = 32 mph

Using foreach with var Keyword

You can use the var keyword for cleaner syntax −

using System;
using System.Collections.Generic;

class Program {
   public static void Main() {
      var colors = new Dictionary<string, string> {
         {"red", "#FF0000"},
         {"green", "#00FF00"},
         {"blue", "#0000FF"}
      };
      
      Console.WriteLine("Color codes:");
      foreach (var color in colors) {
         Console.WriteLine("{0}: {1}", color.Key, color.Value);
      }
   }
}

The output of the above code is −

Color codes:
red: #FF0000
green: #00FF00
blue: #0000FF

Iterating Over Keys Only

When you only need the keys, use the Keys property −

using System;
using System.Collections.Generic;

class Program {
   public static void Main() {
      var students = new Dictionary<string, int> {
         {"Alice", 95},
         {"Bob", 87},
         {"Charlie", 92}
      };
      
      Console.WriteLine("Student names:");
      foreach (var name in students.Keys) {
         Console.WriteLine("- " + name);
      }
   }
}

The output of the above code is −

Student names:
- Alice
- Bob
- Charlie

Iterating Over Values Only

When you only need the values, use the Values property −

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   public static void Main() {
      var scores = new Dictionary<string, int> {
         {"Math", 85},
         {"Science", 92},
         {"English", 78},
         {"History", 88}
      };
      
      Console.WriteLine("All scores:");
      foreach (var score in scores.Values) {
         Console.WriteLine(score);
      }
      
      Console.WriteLine("Average score: " + scores.Values.Average());
   }
}

The output of the above code is −

All scores:
85
92
78
88
Average score: 85.75

Ordered Iteration using LINQ

To iterate in a specific order, use LINQ's OrderBy method −

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   public static void Main() {
      var inventory = new Dictionary<string, int> {
         {"apples", 25},
         {"bananas", 17},
         {"oranges", 32},
         {"grapes", 8}
      };
      
      Console.WriteLine("Sorted by quantity (ascending):");
      var sortedByValue = inventory.OrderBy(x => x.Value);
      foreach (var item in sortedByValue) {
         Console.WriteLine("{0}: {1}", item.Key, item.Value);
      }
      
      Console.WriteLine("\nSorted by name (descending):");
      var sortedByKey = inventory.OrderByDescending(x => x.Key);
      foreach (var item in sortedByKey) {
         Console.WriteLine("{0}: {1}", item.Key, item.Value);
      }
   }
}

The output of the above code is −

Sorted by quantity (ascending):
grapes: 8
bananas: 17
apples: 25
oranges: 32

Sorted by name (descending):
oranges: 32
grapes: 8
bananas: 17
apples: 25

Performance Comparison

Method Use Case Performance
foreach with KeyValuePair Need both keys and values Best performance
foreach with Keys property Need keys only Good performance
foreach with Values property Need values only Good performance
LINQ OrderBy Need sorted iteration Additional sorting overhead

Conclusion

The best way to iterate over a Dictionary in C# is using foreach with KeyValuePair when you need both keys and values. For specific scenarios, use the Keys or Values properties when you only need one part, and combine with LINQ methods like OrderBy when sorted iteration is required.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements