Multiple ways to Iterate Dictionary in C# Examples
Dictionary is a data structure in C#, that stores key and value pairs. This tutorial explains multiple ways to iterate a dictionary object in C# Example
C# Iterate dictionary examples
There are multiple ways to iterate key and value pairs using forEach.
Iterate keys and values using foreach.
Each iteration holds an object of key and value pair, An object contains key and value pair
foreach(var item in employees) {
Console.WriteLine(item.Key + ": " + item.Value);
}
You can also use KeyValuePair<>
generics to hold key and value pair
//Iterate each object with KeyValuePair
foreach(KeyValuePair<int, string> item in employees){
Console.WriteLine(item.Key+": "+item.Value);
}
Another way is to use destructing syntax, which works in .Net 4.7 version onwards.
foreach (var (key, value) in employees) {
Console.WriteLine(key+": "+value);
}
Here is a complete example
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary < int, string > employees = new Dictionary < int, string > ();
employees.Add(1, "one");
employees.Add(2, "four");
employees.Add(3, "two");
employees.Add(4, "three");
// Iterate each object
foreach(var item in employees) {
Console.WriteLine(item.Key + ": " + item.Value);
}
//Iterate each object with KeyValuePair
foreach(KeyValuePair<int, string> item in employees)
{
Console.WriteLine(item.Key+": "+item.Value);
}
}
}
use Dictionary.Values
to iterate only values
use Dictionary.Keys
to iterate only keys.
Here is an example
// Iterate only Values
foreach(var item in employees.Values) {
Console.WriteLine(item);
}
// Iterate only Keys
foreach(var item in employees.Keys) {
Console.WriteLine(item);
}