How to iterate over a dictionary

In C#, you can iterate over a dictionary using a foreach loop. Each iteration gives you a KeyValuePair that contains both the key and value.

You can access the key with .Key and the value with .Value properties. Alternatively, you can use destructuring syntax for cleaner code.

Dictionaries maintain no guaranteed order unless you use an OrderedDictionary or SortedDictionary.

C# Example Code
using System;
using System.Collections.Generic;

public class DictionaryIteration
{
    public static void Main(string[] args)
    {
        var users = new Dictionary<int, string>
        {
            { 1, "Alice" },
            { 2, "Bob" },
            { 3, "Charlie" }
        };

        // Method 1: Using KeyValuePair
        Console.WriteLine("Method 1: KeyValuePair");
        foreach (KeyValuePair<int, string> user in users)
        {
            Console.WriteLine($"ID: {user.Key}, Name: {user.Value}");
        }

        // Method 2: Using var (cleaner)
        Console.WriteLine("\nMethod 2: Using var");
        foreach (var user in users)
        {
            Console.WriteLine($"ID: {user.Key}, Name: {user.Value}");
        }

        // Method 3: Destructuring (C# 7.0+)
        Console.WriteLine("\nMethod 3: Destructuring");
        foreach (var (id, name) in users)
        {
            Console.WriteLine($"ID: {id}, Name: {name}");
        }

        // Iterating only keys
        Console.WriteLine("\nOnly Keys:");
        foreach (var id in users.Keys)
        {
            Console.WriteLine(id);
        }

        // Iterating only values
        Console.WriteLine("\nOnly Values:");
        foreach (var name in users.Values)
        {
            Console.WriteLine(name);
        }
    }
}