Dictionary in C#

Dictionary<TKey, TValue> provide fast lookups, based on keys, to get values. With them, we use keys and values of any type, including int and string. Dictionary is used with different elements. We specify its key type and its value type (string, int).

Define a Dictionary

We specify its key type and its value type (string, int).

Add elements to a Dictionary

Here’s how to add elements to a Dictionary.

Read and update existing values

To read a value use the following statement.

To update an existing value simply use the following.

Check if a key exists in a Dictionary

This sees if a given string is present in a Dictionary.

Iterate through a Dictionary

Here we loop over KeyValuePairs in a Dictionary. With collections like Dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and Value member.

Remove elements from a Dictionary

Here’s how you can remove elements from a Dictionary.

Count elements in a Dictionary

This computes the total number of keys in a Dictionary. This is simpler than accessing the Keys property, or looping over the Dictionary to count it.

Clear all elements from a Dictionary

We can erase all pairs with the Clear method.

Check if a value exists in a Dictionary

This method lacks the constant-time look up speed of ContainsKey. It instead searches the entire collection.

Get all keys of a Dictionary

Here we use the Keys property. We then look through each key and look up the values.