C# Dictionary
In C#, Dictionary<TKey, TValue> is a generic collection that stores data as key-value pairs. Each key identifies one associated value, making a dictionary useful when data must be retrieved by an identifier instead of a numeric position.
Keys in a C# Dictionary must be unique. Values do not have to be unique, so multiple keys may contain the same value.
A dictionary is commonly used for data such as employee IDs and names, product codes and prices, country codes and country names, or configuration names and values.
Define a C# Dictionary
To use a Dictionary, include the System.Collections.Generic namespace. Define the key type and value type inside angle brackets.
Dictionary<keyDatatype, valueDatatype> dictionaryName = new Dictionary<keyDatatype, valueDatatype>();
Example
In the following example, we defined two C# dictionaries named dict1 and dict2.
Program.cs
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
}
}
}
Dictionary dict1 stores key-value pairs where the key is an int and the value is a string.
Dictionary dict2 stores key-value pairs where both the key and value are strings.
Initialize a C# Dictionary with Entries
A C# Dictionary can be initialized by creating an empty dictionary and adding entries later, or by providing the entries in a collection initializer.
The first method is to define a dictionary and add elements to it using the Dictionary.Add() method.
Program.cs
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>();
dict1.Add(1,"Tesla");
dict1.Add(2,"Toyota");
}
}
}
The Add() method inserts a new key-value pair. It throws an ArgumentException when the supplied key already exists in the dictionary.
The second method is to provide the key-value pairs in the definition as shown below.
Program.cs
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
}
}
}
With current C# versions, the repeated type on the right side can also be omitted when the compiler can infer it.
Dictionary<int, string> cars = new();
Add or Replace a C# Dictionary Entry with the Indexer
The dictionary indexer can add a new entry or replace the value of an existing entry.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> cars = new();
cars[1] = "Tesla"; // Adds a new entry
cars[2] = "Honda"; // Adds another entry
cars[2] = "Volkswagen"; // Replaces the value for key 2
Console.WriteLine(cars[2]);
}
}
Volkswagen
Unlike Add(), assigning through the indexer does not fail when the key already exists. It updates the associated value instead.
Read a C# Dictionary Value by Key
Use the key inside square brackets to retrieve its value.
string value = myDictionary[key];
The indexer throws a KeyNotFoundException if the requested key does not exist. When a key may be absent, check it first with ContainsKey() or use TryGetValue().
Check for a Key with ContainsKey()
The ContainsKey() method returns true when a dictionary contains the specified key.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> cars = new()
{
{ 1, "Tesla" },
{ 2, "Honda" }
};
if (cars.ContainsKey(2))
{
Console.WriteLine(cars[2]);
}
}
}
Honda
Safely Retrieve a Dictionary Value with TryGetValue()
TryGetValue() checks for a key and retrieves its value in one operation. It returns true when the key exists and false otherwise.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> cars = new()
{
{ 1, "Tesla" },
{ 2, "Honda" }
};
if (cars.TryGetValue(2, out string? car))
{
Console.WriteLine(car);
}
else
{
Console.WriteLine("Key not found");
}
}
}
Honda
TryGetValue() is generally the clearest approach when the program needs both to test for a key and use its value.
Print All C# Dictionary Key-Value Pairs
Use a foreach loop to access each item in a Dictionary. Each item is a KeyValuePair<TKey, TValue> with Key and Value properties.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
foreach(KeyValuePair<int, string> item in dict1) {
Console.WriteLine(item.Key+" - "+item.Value);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
1 - Tesla
2 - Honda
3 - Toyota
Do not write program logic that depends on a dictionary’s enumeration order. Use an explicitly ordered collection or sort the entries when a particular display order is required.
Iterate Through Dictionary Keys or Values
The Keys property provides the collection of keys, while the Values property provides the collection of values.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> cars = new()
{
{ 1, "Tesla" },
{ 2, "Honda" },
{ 3, "Toyota" }
};
foreach (int key in cars.Keys)
{
Console.WriteLine($"Key: {key}");
}
foreach (string value in cars.Values)
{
Console.WriteLine($"Value: {value}");
}
}
}
Count the Number of Entries in a C# Dictionary
Use the Dictionary.Count property to get the number of key-value pairs currently stored in a dictionary.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
int count = dict1.Count;
Console.WriteLine("Number of items in Dictionary : "+count);
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Number of items in Dictionary : 3
Update a Value for a Key in a C# Dictionary
To update the value associated with a key, use the dictionary indexer. The syntax resembles accessing an array, but the expression inside the brackets is a key rather than a numeric index.
myDictionary[key] = value;
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
dict1[2] = "Volkswagen";
foreach(KeyValuePair<int, string> item in dict1) {
Console.WriteLine(item.Key+" - "+item.Value);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
1 - Tesla
2 - Volkswagen
3 - Toyota
Delete an Entry from a C# Dictionary
Use the Dictionary.Remove(key) method to delete the entry with the specified key. The method returns true when an entry is removed and false when the key is not found.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
dict1.Remove(2);
foreach(KeyValuePair<int, string> item in dict1) {
Console.WriteLine(item.Key+" - "+item.Value);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
1 - Tesla
3 - Toyota
Remove a Dictionary Entry and Retrieve Its Value
An overload of Remove() can return the removed value through an out parameter.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> cars = new()
{
{ 1, "Tesla" },
{ 2, "Honda" }
};
if (cars.Remove(2, out string? removedCar))
{
Console.WriteLine($"Removed: {removedCar}");
}
}
}
Removed: Honda
Remove All Entries with Dictionary.Clear()
Call Clear() to remove every key-value pair from a dictionary. The dictionary object remains available and can receive new entries afterward.
Dictionary<int, string> cars = new()
{
{ 1, "Tesla" },
{ 2, "Honda" }
};
cars.Clear();
Console.WriteLine(cars.Count);
0
Check Whether a C# Dictionary Contains a Value
Use ContainsValue() when you need to test whether a particular value appears in the dictionary.
bool containsValue = cars.ContainsValue("Honda");
Searching by key is the primary use case for a dictionary. If a program frequently searches by value, consider whether another data structure or an additional lookup is more suitable.
Use Case-Insensitive String Keys in a C# Dictionary
By default, string keys are case-sensitive. Pass a string comparer to the constructor when keys such as "ADMIN" and "admin" should be treated as equivalent.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, string> roles =
new(StringComparer.OrdinalIgnoreCase)
{
{ "admin", "Full access" }
};
Console.WriteLine(roles["ADMIN"]);
}
}
Full access
StringComparer.OrdinalIgnoreCase is appropriate for many programmatic identifiers. Choose a comparer that matches the meaning of the keys in the application.
C# Dictionary Methods and Properties
| Member | Purpose |
|---|---|
Add(key, value) | Adds a new key-value pair and fails if the key already exists. |
dictionary[key] | Reads, adds, or replaces the value associated with a key. |
TryAdd(key, value) | Attempts to add an entry and returns whether it was added. |
ContainsKey(key) | Checks whether a key exists. |
TryGetValue(key, out value) | Safely retrieves a value when the key exists. |
ContainsValue(value) | Checks whether a value occurs in the dictionary. |
Remove(key) | Removes the entry associated with a key. |
Clear() | Removes all entries. |
Count | Returns the number of entries. |
Keys | Returns a collection containing the keys. |
Values | Returns a collection containing the values. |
C# Dictionary Key Requirements
A dictionary determines where to store and find an entry by using the key’s equality and hash-code behavior. A suitable key should therefore have stable equality and hash-code values while it is stored in the dictionary.
- Each key must be unique according to the dictionary’s comparer.
- A key cannot be
nullwhen the dictionary’s key type does not permit it. - Custom key types should implement equality and hash-code behavior consistently.
- A key should not be changed in a way that alters its equality or hash code after insertion.
C# Dictionary and List Differences
| Dictionary | List |
|---|---|
| Stores key-value pairs. | Stores individual values. |
| Retrieves values by a unique key. | Retrieves values primarily by numeric index. |
| Does not permit duplicate keys. | Permits duplicate values. |
| Best when each value has a meaningful identifier. | Best when items form a sequence. |
Common C# Dictionary Errors
- Adding a duplicate key:
Add()throws an exception if the key already exists. UseTryAdd(), checkContainsKey(), or assign through the indexer when replacement is intended. - Reading a missing key: The indexer throws
KeyNotFoundException. UseTryGetValue()when absence is expected. - Modifying entries during enumeration: Adding or removing entries inside a normal
foreachloop invalidates the enumeration. - Assuming keys are sorted: A Dictionary is not a sorted-key collection. Use
SortedDictionary<TKey, TValue>or sort the data separately when sorted output is required. - Using mutable objects as keys: Changing fields involved in equality or hash-code calculation can make an inserted key difficult to locate.
C# Dictionary FAQs
Can a C# Dictionary contain duplicate values?
Yes. Dictionary values may be duplicated. Only keys must be unique.
What happens when a duplicate key is added to a Dictionary?
Add() throws an ArgumentException. TryAdd() returns false, while assignment through the indexer replaces the existing value.
How do I avoid KeyNotFoundException in a C# Dictionary?
Use TryGetValue() when a key may not exist. It checks for the key and returns the value without throwing an exception for a missing key.
Is a C# Dictionary thread-safe?
A regular Dictionary<TKey, TValue> does not support unsynchronized concurrent writes. Coordinate access with synchronization or use ConcurrentDictionary<TKey, TValue> when multiple threads must update the collection.
How do I sort a C# Dictionary?
A Dictionary is not inherently sorted. Sort its entries with LINQ for display or use SortedDictionary<TKey, TValue> when entries need to remain ordered by key.
C# Dictionary Summary
In this C# Tutorial, we learned how to define and initialize a Dictionary, add and update entries, safely retrieve values, iterate through keys and values, count entries, remove data, use case-insensitive keys, and avoid common dictionary errors.
TutorialKart.com