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.
This class is defined in the System.Collections.Generic namespace, so you should import or using System.Collections.Generic namespace.
- TKey - The type of the keys in the dictionary.
- TValue - The type of the values in the dictionary.
C# Dictionary examples
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.
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
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.
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
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.
- In .NET 3.5 It is in System.ServiceModel.Web.dll
- 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.
|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.|
|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
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
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