C# Dictionary

How to C# Dictionary

A Dictionary class is a data structure that represents a collection of keys and values pair of data. The key is identical in a key-value pair and it can have at most one value in the dictionary, but a value can be associated with many different keys.

How to C# Dictionary C# Dictionary Examples

This class is defined in the System.Collections.Generic namespace, so you should import or using System.Collections.Generic namespace.


  1. TKey - The type of the keys in the dictionary.
  2. TValue - The type of the values in the dictionary.


C# Dictionary examples

C# dictionary example

Adding Values to Dictionary

Add method in Dictionary takes two parameters , one for the key and one for the value.



Key in a Dictionary should not be null , but a value can be, if TValue is a reference type. The following dictionary example creates an empty Dictionary < TKey,TValue > of strings with string keys and uses the Add method to add some elements.

foreach in Dictionary

Retrieve Key-Value pair from Dictionary using foreach loop.

Dictionary exceptions

When you adds an item to the dictionary if item already exists in the dictionary an exception will be thrown.

However, if the specified key already exists in the Dictionary, setting the Item[TKey] property overwrites the old value. In contrast, the Add method throws an exception if a value with the specified key already exists.

Indexer or Dictionary[Key]

When you add item using indexer , if the key doesn't exist in the dictionary, a new item will be added. If the key exists then the value will be updated with the new value.


Search for a Key

C# Dictionary search key value

We can search a Key in Dictionary by using the ContainsKey method to test whether a key exists or not. ContainsKey computes the hashcode for its argument and checks the internal structures in the Dictionary.

How Fast...

Accessing a value by using its key is very fast, close to O(1), because the C# Dictionary class is implemented as a hash table. The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey in the Dictionary object.

Dictionary TryGetValue

When a program often has to try keys that turn out not to be in the dictionary, TryGetValue can be a more efficient way to retrieve values. When this method returns, contains the value associated with the specified key, if the key is found; otherwise, method will return false if it could not found keys instead of throwing an exception.

Dictionary: TryGetValue Vs ContainsKey

Which is more efficient: Dictionary TryGetValue or dictionary ContainsKey

Dictionary TryGetValue will be faster when compare to ContainsKey. The ContainsKey method uses the same check as TryGetValue, which internally refers to the actual entry location. The Item property actually has nearly identical code functionality as TryGetValue , except that it will throw an exception instead of returning false. When using ContainsKey followed by the Item actually duplicates the lookup functionality, which is the bulk of the computation in this case.

Get dictionary value by key

Note that if the dictionary doesn't have a key that equals "2", that code will throw an exception . If you want to check first, you can use TryGetValue like this:

Get dictionary key by value

In some situations, you have only dictionary value and you have to find the key. The following example will help you to find the key using value.

How to get value of Dictionary keys via index ?

A dictionary does not use index since it is not its initial purpose. A dictionary uses key-value relation . It does not so because items are not stored continuously in memory . You have one reference which knows where all items are. But none is first or last. If you want to get item by index, you have to loop through all the elements in dictionary.

Convert C# dictionary to a JSON String

Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize , you can write a method for your specific type. For a Dictionary < int, List < int > > , you can using the following example.

The System.Runtime.Serialization.Json Namespace is in two different DLL's depending on your .net framework.

  1. In .NET 3.5 It is in System.ServiceModel.Web.dll
  2. In .NET 4.0 and above It is in System.Runtime.Serialization.dll

Dictionary Count Property

C# Dictionary count property returns the number of key/value pairs contained in the dictionary.

Remove Item from Dictionary

The Remove() method removes an item with the specified key from the dictionary collection.

Remove All Item from Dictionary

The Dictionary Clear() method removes all items from the collection.

Property Description
Count Get the number of elements that are actually in the Dictionary.
Keys Gets a collection containing the keys in the Dictionary.
Values Gets a collection containing the values in the Dictionary.

Methods Description
Add(Key, Value) Adds the specified key and value to the dictionary.
ContainsKey(Key) Determines whether the Dictionary contains the specified key.
ToString() Returns a string that represents the current object.

Iterate over a Dictionary

There are many different ways to iterate over a Dictionary in C#. From the following link you can see in detail .... How to Iterate over a Dictionary

Dictionary Versus HashTable

C# Dictionary and HashTable

Dictionary is a generic type , Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out. Since both Dictionary and Hashtable are internally hashtables, so fast access to many-item data according to key, also both need immutable and unique keys. More about.... Dictionary Vs HashTable

Dictionary Versus List

C# Dictionary and List

Both lists and dictionaries are used to store collections of data. The Dictionary is based on a hash table, that means it uses a hash lookup, which is a rather efficient algorithm to look up things, on the other hand, a list you have to go element by element until it finds the result from beginning to the result each time. More about.... Dictionary vs List
 (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About