C# Dictionary

In C#, the Dictionary provides a collection of values that can be identified and retrieved by using keys rather than indexes. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast.

The Dictionary<TKey, TValue> class implements this functionality by internally maintaining two arrays, one for the keys from which you’re mapping and one for the values to which you’re mapping.

When you insert a key/value pair into a Dictionary<TKey, TValue> collection, it automatically tracks which key belongs to which value and makes it possible for you to retrieve the value that is associated with a specified key quickly and easily.

Important points about C# Dictionary:

  • A Dictionary<TKey, TValue> collection cannot contain duplicate keys. If you call the Add method to add a key that is already present in the keys array, you’ll get an exception.
  • A Dictionary<TKey, TValue> collection is a sparse data structure that operates most efficiently when it has plenty of memory with which to work. The size of a Dictionary<TKey,TValue> collection in memory can grow quite quickly as you insert more elements.
  • When you use a foreach statement to iterate through a Dictionary<TKey, TValue> collection, you get back a KeyValuePair<TKey, TValue> item and you can access each element through the Key property and the Value property. These elements are read-only; you cannot use them to modify the data in the Dictionary<TKey, TValue> collection.
  • Dictionary is an unordered data structure.
  • Dictionary implements IEnumerable

C# Dictionary Declaration and Initialization

When creating a dictionary, we first have to define the key and the value. Also make sure that you have the System.Collections.Generic; imported.

Dictionary<TKey,TValue> dict= new Dictionary<TKey,TValue>();

Where, TKey = The type of the keys in the dictionary.

TValue= The type of the values in the dictionary.

Example:

Dictionary<string, string> dict = new Dictionary<string, string>();

OR

Dictionary<string, int> dictionary =new Dictionary<string, int>();

Adding values in C# Dictionary

You can add values in dictionary by using .Add(Tkey, TValue) method, for example, if consider above dictionary, where we have key = string and value = int

dictionary.Add("linux", 1);
dictionary.Add("windows", 2);
dictionary.Add("mac", 3);

Delete or Remove item from Dictionary

To delete a value from a dictionary, there is the .Remove() method that we are already familiar with. For this we have to address the dictionary with its name and enter the key to be deleted in the Remove method.

dictionary.Remove("mac");

C# dictionary example using foreach loop to iterate and print value

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		Dictionary<string, int> dictionary =new Dictionary<string, int>();
		
		//add items in dictionary
		dictionary.Add("linux", 1);
		dictionary.Add("windows", 2);
		dictionary.Add("mac", 3);
		
		//PrintDictionary
	 	Console.WriteLine("Dictionary after adding values:");
		ForEachDictionary(dictionary);
		Console.WriteLine();
		
		//remove item from dictionary
		dictionary.Remove("mac");
		Console.WriteLine("Dictionary after removing a value:");
		ForEachDictionary(dictionary);
	}
	//print dictionary using foreach loop
	public static void ForEachDictionary(Dictionary<string, int> dictionary)
	{
		foreach(KeyValuePair<string, int> kvp in dictionary)
		{
			Console.WriteLine("Key: "+kvp.Key +" Value:"+kvp.Value);
		}

	}
}

Output:

Dictionary after adding values:
Key: linux Value:1
Key: windows Value:2
Key: mac Value:3

Dictionary after removing a value:
Key: linux Value:1
Key: windows Value:2

In the above example, we creating a dictionary which has string type key and int type value.

We are also looping the dictionary using foreach value and printing key/value using it.

C# dictionary get value by key

To get the value using Key in C# dictionary, we can use TryGetValue() Method

TryGetValue() Signature:

bool TryGetValue(TKey key, out TValue value)

Indexer takes the key as a parameter. If the specified key does not exist then a KeyNotFoundException will be thrown.

If you are not sure about the key then use the TryGetValue() method. The TryGetValue() method will return false if it could not found keys instead of throwing an exception.

Considering above example dictionary, we can try this example

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		
		Dictionary<string, int> dictionary =new Dictionary<string, int>();
		
		//add items in dictionary
		dictionary.Add("linux", 1);
		dictionary.Add("windows", 2);
		dictionary.Add("mac", 3);
		
		
		int result;
                //Get value using Key
		if(dictionary.TryGetValue("windows", out result))
		{
			Console.WriteLine(result);
		}
		else
		{
			Console.WriteLine("Could not find the specified key.");
		}
	}
}

Output:

2

As the key = windows, exists in above dictionary, we were able to get's it value, which is, 2.


Share Tweet