dict.Keys / Values / foreach
| Since: | C# 2.0(2005) |
|---|
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
Program.cs
using System;
using System.Collections.Generic;
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}");
}
Run the following command:
dotnet run --- Countries --- Japan France Germany --- Capitals --- Tokyo Paris Berlin --- Countries and Capitals --- The capital of Japan is Tokyo. The capital of France is Paris. The capital of Germany is Berlin. --- Tuple Deconstruction --- Japan → Tokyo France → Paris Germany → Berlin
Common Mistakes
Common Mistake: Modifying the Dictionary During a foreach Loop Throws an Exception
The collections returned by Keys and Values are live views of the dictionary. Adding or removing entries while iterating with foreach throws an InvalidOperationException.
using System;
using System.Collections.Generic;
// NG: modifying the dictionary inside a foreach loop
Dictionary<string, int> dict = new Dictionary<string, int>
{
{ "a", 1 }, { "b", 2 }, { "c", 3 }
};
// foreach (var pair in dict)
// {
// if (pair.Value == 2) dict.Remove(pair.Key); // InvalidOperationException!
// }
The same logic can also be written as:
using System;
using System.Collections.Generic;
using System.Linq;
// OK: collect the keys to remove first, then delete them outside the loop
Dictionary<string, int> dict = new Dictionary<string, int>
{
{ "a", 1 }, { "b", 2 }, { "c", 3 }
};
List<string> toRemove = dict.Keys.Where(k => dict[k] == 2).ToList();
foreach (string key in toRemove)
{
dict.Remove(key);
}
Console.WriteLine(dict.Count); // 2
Console.WriteLine(string.Join(", ", dict.Keys)); // a, c
Run the following command:
dotnet run 2 a, c
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.