dict.Keys / Values / foreach
How to use Keys to retrieve all keys, Values to retrieve all values, and foreach to iterate over every entry in a Dictionary<TKey, TValue>.
Syntax
using System.Collections.Generic;
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
// Retrieves all keys.
ICollection<TKey> keys = dict.Keys;
// Retrieves all values.
ICollection<TValue> values = dict.Values;
// Iterates over key-value pairs with foreach.
foreach (KeyValuePair<TKey, TValue> pair in dict)
{
// Access the key with pair.Key and the value with pair.Value.
}
Property / Syntax List
| Property / Syntax | Description |
|---|---|
| Keys | Returns all keys in the dictionary as ICollection<TKey>. |
| Values | Returns all values in the dictionary as ICollection<TValue>. |
| foreach (KeyValuePair<K,V> pair in dict) | Enumerates every entry in the dictionary as a key-value pair. |
| Count | Returns the number of entries stored in the dictionary. |
Sample Code
using System;
using System.Collections.Generic;
// Creates a dictionary of countries and their capitals.
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "Japan", "Tokyo" },
{ "France", "Paris" },
{ "Germany", "Berlin" }
};
// Uses Keys to iterate over the list of countries.
Console.WriteLine("--- Countries ---");
foreach (string country in capitals.Keys)
{
Console.WriteLine(country);
}
// Uses Values to iterate over the list of capitals.
Console.WriteLine("--- Capitals ---");
foreach (string city in capitals.Values)
{
Console.WriteLine(city);
}
// Uses KeyValuePair to access both the key and value at once.
Console.WriteLine("--- Countries and Capitals ---");
foreach (KeyValuePair<string, string> pair in capitals)
{
Console.WriteLine($"The capital of {pair.Key} is {pair.Value}.");
}
// From C# 7.0 onward, you can use tuple deconstruction for brevity.
Console.WriteLine("--- Tuple Deconstruction ---");
foreach ((string countryName, string cityName) in capitals)
{
Console.WriteLine($"{countryName} → {cityName}");
}
Notes
The collections returned by Keys and Values are live views of the dictionary. Any changes to the dictionary are reflected in a collection you already obtained. Adding or removing entries while iterating with foreach throws an InvalidOperationException. If you need to modify the dictionary during a loop, take a snapshot first by calling ToList().
Enumeration order may vary depending on the .NET runtime. If you need insertion-order guarantees, consider using SortedDictionary<TKey, TValue> (available from C# 8.0 onward). For adding and removing entries, see dict.Add() / Remove() / Clear(). For safe value retrieval, see dict.TryGetValue() / ContainsKey().
If you find any errors or copyright issues, please contact us.