Dictionary in C#: Add, Read, Loop, Sort and Update (.NET 10)

If you need to find a value by a key, like a state capital from the code “TX”, a dictionary in C# is the answer: Dictionary<TKey, TValue> maps unique keys to values and finds any key in close to constant time.

In this tutorial, I’ll use one small map of US state capitals to teach the dictionary in C# on .NET 10. You’ll add, read, update, remove, loop, sort and convert it, and you’ll see the real exceptions each mistake throws.

I’ll also tell you which method I’d pick for each job, so you don’t have to guess.

The Sample Dictionary We’ll Use: US State Capitals

Every method below works on the same dictionary: five state codes as keys and their capitals as values. Here’s how I create it with a collection initializer:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia",
    ["TX"] = "Austin",
    ["CA"] = "Sacramento",
    ["NY"] = "Albany",
    ["FL"] = "Tallahassee"
};

Console.WriteLine($"States: {capitals.Count}");
Console.WriteLine($"TX -> {capitals["TX"]}");

// The older { key, value } initializer works too
var codes = new Dictionary<string, int>
{
    { "WA", 53 }, { "TX", 48 }
};
Console.WriteLine($"FIPS code for WA: {codes["WA"]}");

Output:

States: 5
TX -> Austin
FIPS code for WA: 53
Dictionary in C# created with a collection initializer mapping US state codes WA, TX, CA, NY and FL to capitals, running in VS Code
Five state capitals, then a lookup of TX

The program prints a count of 5 and TX -> Austin.

How does this code work?

Dictionary<string, string> says both keys and values are strings. The ["WA"] = "Olympia" lines are index initializers; each one calls the indexer setter while the object is built.

The second dictionary uses the older { key, value } form, which calls Add() instead. Both live in System.Collections.Generic, which .NET 10 imports for you through implicit usings.

Keys must be unique and can’t be null; values can repeat and can be null. If you only need values by position, a List in C# is the simpler choice.

Method 1: Add Items to a Dictionary with Add() or the Indexer

Same dictionary, now growing. There are two ways to put a key in a dictionary, and they behave differently when the key already exists:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

capitals.Add("NV", "Carson City");     // new: added
capitals["OR"] = "Salem";              // new: added
capitals["TX"] = "Austin (updated)";   // exists: replaced
Console.WriteLine($"Count: {capitals.Count}");
Console.WriteLine($"TX -> {capitals["TX"]}");

capitals.Add("TX", "Houston");         // duplicate: throws

Output:

Count: 5
TX -> Austin (updated)
Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: TX
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Program.<Main>$(String[] args) in C:\DotNetDemo\DictionaryDemo\AddVsIndexer.cs:line 12
C# dictionary Add method throwing ArgumentException An item with the same key has already been added. Key: TX in the VS Code terminal
The indexer overwrites TX; Add throws on the duplicate

The count reaches 5, TX reads Austin (updated), and then line 12 crashes with an ArgumentException.

How does this code work?

Add("NV", "Carson City") inserts a new pair. The indexer capitals["OR"] = "Salem" also inserts, because OR isn’t there yet.

capitals["TX"] = ... hits an existing key, so the indexer quietly replaces the value. Add("TX", ...) refuses to do that and throws, which is exactly what you want when a duplicate means bad data.

Important: don’t wrap Add() in a try-catch block to skip duplicates. Use TryAdd() from Method 3; it’s cheaper and says what you mean.

Method 2: Read Dictionary Values with TryGetValue (Recommended)

Reading is where most dictionary bugs live. Here’s what the plain indexer does with a key that isn’t there, using a two-state version of the same dictionary:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin"
};

Console.WriteLine(capitals["OH"]);

Output:

Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'OH' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at Program.<Main>$(String[] args) in C:\DotNetDemo\DictionaryDemo\MissingKey.cs:line 6

That KeyNotFoundException names the missing key, which helps, but it still stops the program. So I check first, and TryGetValue does the check and the read in one hash lookup:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento",
    ["NY"] = "Albany", ["FL"] = "Tallahassee"
};

// One lookup: TryGetValue
if (capitals.TryGetValue("CA", out string? city))
    Console.WriteLine($"CA -> {city}");
if (!capitals.TryGetValue("OH", out _))
    Console.WriteLine("OH is not in the dictionary");

// Two lookups: ContainsKey, then the indexer
if (capitals.ContainsKey("NY"))
    Console.WriteLine($"NY -> {capitals["NY"]}");
bool hasAustin = capitals.ContainsValue("Austin");
Console.WriteLine($"Has the value Austin: {hasAustin}");

Output:

CA -> Sacramento
OH is not in the dictionary
NY -> Albany
Has the value Austin: True
C# dictionary TryGetValue with an out variable and ContainsKey before the indexer, output in the VS Code terminal
TryGetValue finds CA and reports that OH is missing

CA comes back as Sacramento, OH is reported missing, NY reads Albany, and ContainsValue("Austin") is True.

How does this code work?

TryGetValue returns true or false and hands the value back through out string? city. The ? matters: when the key is missing, city is null.

ContainsKey plus the indexer works too, but it hashes the key twice. ContainsValue is the slow one: it scans every entry, the same way you’d search a string array for an element.

Method 3: Dictionary TryAdd, GetValueOrDefault and Remove(key, out value)

These three methods replace most of the if-checks people write around a dictionary. Same dictionary again, trimmed to three capitals:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

Console.WriteLine($"TryAdd NV: {capitals.TryAdd("NV", "Carson City")}");
Console.WriteLine($"TryAdd TX: {capitals.TryAdd("TX", "Houston")}");

Console.WriteLine($"OH: '{capitals.GetValueOrDefault("OH")}'");
Console.WriteLine($"OH: {capitals.GetValueOrDefault("OH", "unknown")}");

if (capitals.Remove("CA", out string? removed))
    Console.WriteLine($"Removed CA ({removed}), {capitals.Count} left");
Console.WriteLine($"Remove OH: {capitals.Remove("OH")}");

Output:

TryAdd NV: True
TryAdd TX: False
OH: ''
OH: unknown
Removed CA (Sacramento), 3 left
Remove OH: False

NV is added, TX is not, OH falls back to an empty string and then to unknown, and CA is removed with its value, leaving 3 entries.

How does this code work?

TryAdd adds only when the key is new and returns false instead of throwing. That’s why the second call can’t replace Austin with Houston.

GetValueOrDefault returns default(TValue), which is null for a string, unless you pass your own fallback. It’s an extension method on IReadOnlyDictionary, so it saves you a null check at the call site.

Remove("CA", out string? removed) deletes the key and gives you the old value in one step. The plain Remove("OH") just returns false for a missing key; it never throws.

Method 4: Loop Through a Dictionary with foreach

Each item you get from a dictionary is a KeyValuePair<TKey, TValue>. The foreach loop in C# is the natural way to walk them:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

foreach (KeyValuePair<string, string> pair in capitals)
    Console.WriteLine($"{pair.Key}: {pair.Value}");

foreach (var (code, city) in capitals)      // deconstruction
    Console.WriteLine($"{city} is the capital of {code}");

Console.WriteLine(string.Join(", ", capitals.Keys));
Console.WriteLine(string.Join(", ", capitals.Values));

Output:

WA: Olympia
TX: Austin
CA: Sacramento
Olympia is the capital of WA
Austin is the capital of TX
Sacramento is the capital of CA
WA, TX, CA
Olympia, Austin, Sacramento
Loop through a C# dictionary with foreach over KeyValuePair, tuple-style deconstruction, Keys and Values, VS Code output
KeyValuePair, deconstruction, then the Keys and Values collections

All three passes list WA, TX and CA in the order I added them.

How does this code work?

The first loop reads pair.Key and pair.Value. The second deconstructs each pair into two variables, the same syntax you’d use with a tuple in C#.

Keys and Values are live collections, and string.Join turns them into one line, like when you convert a list to a comma-separated string.

Important: Microsoft documents the enumeration order as undefined. It looks like insertion order here, but after removals new items can fill old slots, so never rely on it.

How Do You Update Values in a C# Dictionary?

Updating is just the indexer again. A common job is counting: here I tally six orders by state code, the same keys as our capitals:

using static System.Runtime.InteropServices.CollectionsMarshal;

string[] orders = ["TX", "WA", "TX", "CA", "TX", "WA"];
var perState = new Dictionary<string, int>();

foreach (string state in orders)
    perState[state] = perState.GetValueOrDefault(state) + 1;
Console.WriteLine(string.Join(", ", perState));

// .NET 6+: one hash lookup per item instead of two
var fast = new Dictionary<string, int>();
foreach (string state in orders)
    GetValueRefOrAddDefault(fast, state, out _)++;
Console.WriteLine(string.Join(", ", fast));

Output:

[TX, 3], [WA, 2], [CA, 1]
[TX, 3], [WA, 2], [CA, 1]
Update values in a C# dictionary by counting orders per state with GetValueOrDefault and CollectionsMarshal.GetValueRefOrAddDefault, VS Code output
Both versions count TX 3, WA 2, CA 1

Both lines print [TX, 3], [WA, 2], [CA, 1].

How does this code work?

perState.GetValueOrDefault(state) + 1 reads 0 for a new state, adds one and writes it back through the indexer. That’s two lookups per order, which is fine for almost every app.

CollectionsMarshal.GetValueRefOrAddDefault (.NET 6+) returns a ref to the value slot, adding a 0 entry if needed, so ++ updates it in place; using static lets me call it without the class name. Don’t add or remove keys while you hold that ref.

Changing Values Inside a foreach Loop

Can you update while you loop over the same capitals? Overwriting existing keys is fine; adding a new key isn’t:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

foreach (string code in capitals.Keys)
    capitals[code] = capitals[code].ToUpperInvariant();   // overwrite: fine
Console.WriteLine(string.Join(", ", capitals));

foreach (string code in capitals.Keys)
    capitals[code + "-2"] = "copy";                      // new key: throws

Output:

[WA, OLYMPIA], [TX, AUSTIN], [CA, SACRAMENTO]
Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator.MoveNext()
   at Program.<Main>$(String[] args) in C:\DotNetDemo\DictionaryDemo\UpdateInLoop.cs:line 10

On .NET 10 the first loop uppercases all three capitals. The second loop adds a key and throws InvalidOperationException on the next step of the enumerator. If you must add while looping, loop over a copy such as capitals.Keys.ToList().

Case-Insensitive Dictionary Keys with StringComparer.OrdinalIgnoreCase

By default string keys are case-sensitive, so “tx” and “TX” are different keys. Pass a comparer to the constructor and the same capitals accept any casing:

var capitals = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

Console.WriteLine($"tx -> {capitals["tx"]}");
Console.WriteLine($"Contains 'ca': {capitals.ContainsKey("ca")}");
Console.WriteLine($"TryAdd 'wa': {capitals.TryAdd("wa", "Seattle")}");

var strict = new Dictionary<string, string> { ["TX"] = "Austin" };
Console.WriteLine($"Default comparer, 'tx' found: {strict.ContainsKey("tx")}");

Output:

tx -> Austin
Contains 'ca': True
TryAdd 'wa': False
Default comparer, 'tx' found: False

“tx” finds Austin, “ca” is found, “wa” can’t be added as a second key, and the default dictionary doesn’t find “tx” at all.

How does this code work?

The comparer decides both the hash code and equality for every key. OrdinalIgnoreCase is fast and culture-neutral, so it’s my pick for codes, file names and IDs; you’ll see the same idea when you compare a string with multiple values.

Pro Tip: the comparer is fixed once the dictionary exists. To change it, build a new one: new Dictionary<string, string>(old, StringComparer.OrdinalIgnoreCase).

How to Sort a Dictionary by Key or Value in C#

A dictionary has no order to sort, so you sort a view of it with LINQ, or you switch to a type that keeps keys sorted. Same five capitals:

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento",
    ["NY"] = "Albany", ["FL"] = "Tallahassee"
};

Console.WriteLine("By key:   " + string.Join(", ",
    capitals.OrderBy(kv => kv.Key).Select(kv => kv.Key)));
Console.WriteLine("By value: " + string.Join(", ",
    capitals.OrderBy(kv => kv.Value).Select(kv => kv.Value)));

var sorted = new SortedDictionary<string, string>(capitals);
Console.WriteLine("Sorted: " + string.Join(", ", sorted.Keys));

Output:

By key:   CA, FL, NY, TX, WA
By value: Albany, Austin, Olympia, Sacramento, Tallahassee
Sorted: CA, FL, NY, TX, WA
Sort a C# dictionary by key and by value with LINQ OrderBy and a SortedDictionary, output in the VS Code terminal
OrderBy by key, by value, and a SortedDictionary

By key you get CA, FL, NY, TX, WA; by value Albany comes first and Tallahassee last.

How does this code work?

OrderBy(kv => kv.Key) returns a sorted sequence of pairs and leaves the dictionary untouched. Use OrderByDescending for the reverse, just as you would to sort an array in C#.

SortedDictionary keeps its keys in order all the time, at the cost of O(log n) lookups instead of near O(1).

Create a Dictionary from a List with ToDictionary

Real data usually arrives as a list of records, not as pairs. LINQ’s ToDictionary builds the same capitals map from it:

State[] states =
[
    new("WA", "Washington", "Olympia"),
    new("TX", "Texas", "Austin"),
    new("CA", "California", "Sacramento")
];

Dictionary<string, string> capitals = states.ToDictionary(s => s.Code, s => s.Capital);
Dictionary<string, State> byCode = states.ToDictionary(s => s.Code);

Console.WriteLine($"TX -> {capitals["TX"]}");
Console.WriteLine($"CA -> {byCode["CA"].Name}");

record State(string Code, string Name, string Capital);

Output:

TX -> Austin
CA -> California

TX maps to Austin, and the second dictionary returns the whole record, so CA gives California.

How does this code work?

The first lambda picks the key and the optional second one picks the value. Without it, the value is the whole object, here a record like the ones in my structure in C# guide.

Important: ToDictionary calls Add under the hood, so a duplicate code in the list throws the same ArgumentException you saw in Method 1.

Dictionary vs SortedDictionary vs ConcurrentDictionary vs FrozenDictionary vs Hashtable

Dictionary isn’t the only key/value type in .NET 10. Here’s how I choose, with the older Hashtable in C# included for legacy code:

TypeUse it whenLookupNotes
Dictionary<K,V>Most code, one threadNear O(1)Order undefined
SortedDictionary<K,V>You need keys in orderO(log n)Sorted by key comparer
ConcurrentDictionary<K,V>Many threads read and writeNear O(1)TryAdd, AddOrUpdate, GetOrAdd
FrozenDictionary<K,V>Build once, read many times (.NET 8+)Fastest readsImmutable, slower to create
HashtableOld non-generic code onlyNear O(1)Stores object, needs casts

Freezing the same capitals takes one call to ToFrozenDictionary() from System.Collections.Frozen:

using System.Collections.Frozen;

var capitals = new Dictionary<string, string>
{
    ["WA"] = "Olympia", ["TX"] = "Austin", ["CA"] = "Sacramento"
};

FrozenDictionary<string, string> lookup = capitals.ToFrozenDictionary();
Console.WriteLine($"TX -> {lookup["TX"]}, count {lookup.Count}");
Console.WriteLine(lookup is IDictionary<string, string> d && d.IsReadOnly);

Output:

TX -> Austin, count 3
True

It still finds Austin, and it reports itself as read-only. Microsoft recommends the generic types over Hashtable and the old ArrayList in C#, because they’re type-safe and avoid boxing.

Which Dictionary Method Should You Use?

TaskMy pickWhy
Add a new key, duplicates are bugsAddThrows on a duplicate
Add only if missingTryAddReturns false, no exception
Add or overwriteIndexer d[key] = valueNever throws
Read a key that may be missingTryGetValueOne lookup, no exception
Read with a fallbackGetValueOrDefaultOne line
Remove and keep the valueRemove(key, out v)One lookup
Count or accumulateIndexer + GetValueOrDefaultReadable; ref API only in hot loops

If your keys are a fixed set of names, an enum in C# as the key type keeps typos out at compile time.

Things to Keep in Mind

  • The indexer throws on a missing key. Read with TryGetValue or GetValueOrDefault unless the key is guaranteed.
  • Add throws on a duplicate key. Use the indexer to overwrite or TryAdd to skip.
  • Order isn’t guaranteed. Sort with LINQ or use SortedDictionary when order matters.
  • String keys are case-sensitive. Pass StringComparer.OrdinalIgnoreCase to the constructor for codes and IDs.
  • Dictionary isn’t thread-safe for writes. Switch to ConcurrentDictionary when several threads update it.

Ready for the next collection? These pick up where this one stops:

Frequently Asked Questions

What is a dictionary in C#?

A Dictionary<TKey, TValue> is a generic collection in System.Collections.Generic that stores unique keys, each mapped to one value. It’s a hash table, so finding a value by its key is close to O(1).

Can a C# dictionary have duplicate keys?

No. Add throws an ArgumentException for a duplicate key and the indexer overwrites the old value. Values can repeat. For one key with many values, store a list as the value, such as Dictionary<string, List<string>>.

Can a dictionary key be null in C#?

No. A null key throws ArgumentNullException. Values can be null when TValue is a reference type or a nullable value type.

Is a C# dictionary ordered?

No. The Dictionary<TKey,TValue> reference on Microsoft Learn says the enumeration order is undefined. Use SortedDictionary for key order or sort with LINQ when you display it.

What is the difference between Dictionary and Hashtable in C#?

Dictionary is generic and type-safe, so there’s no casting or boxing. Hashtable is the older non-generic type that stores object keys and values; keep it only for legacy code.

Is Dictionary thread-safe in C#?

It supports several readers at once as long as nothing writes. If any thread adds, removes or updates while others read, use ConcurrentDictionary<TKey, TValue> instead.