C# - Dictionary

The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no particular order.

Dictionary Characteristics

  • Dictionary<TKey, TValue> stores key-value pairs.
  • Comes under System.Collections.Generic namespace.
  • Implements IDictionary<TKey, TValue> interface.
  • Keys must be unique and cannot be null.
  • Values can be null or duplicate.
  • Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
  • Elements are stored as KeyValuePair<TKey, TValue> objects.

Creating a Dictionary

You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store. The following example shows how to create a dictionary and add key-value pairs.

Example: Create Dictionary and Add Elements
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");

//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three"); 

foreach(KeyValuePair<int, string> kvp in numberNames)
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
		
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};
		
foreach(var kvp in cities)
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

In the above example, numberNames is a Dictionary<int, string> type dictionary, so it can store int keys and string values. In the same way, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionary cannot include duplicate or null keys, whereas values can be duplicated or null. Keys must be unique otherwise, it will throw a runtime exception.

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

String[] args in C#