Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. It's a generic type, which is defined under System.Collections.Generic namespace. It's dynamic in nature, meaning the size of the dictionary is growing as needed.
- Key-Value Pair: The value is stored in the Key-Value pair.
- Efficient Lookup: It provides fast lookups for values based on keys.
- Unique Keys: Stored keys uniquely and adding duplicate keys results in a runtime exception.
Example 1: Creating and Displaying a Dictionary
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a dictionary
Dictionary<int, string> sub = new Dictionary<int, string>();
// Adding elements
sub.Add(1, "C#");
sub.Add(2, "Javascript");
sub.Add(3, "Dart");
// Displaying dictionary
foreach (var ele in sub){
Console.WriteLine($"Key: {ele.Key}, Value: {ele.Value}");
}
}
}
Output
Key: 1, Value: C# Key: 2, Value: Javascript Key: 3, Value: Dart
Steps to Create a Dictionary
Step 1: Include System.Collections.Generic namespace
using System.Collections.Generic;
Step 2: Create a Dictionary using Dictionary<TKey, TValue> class
Dictionary<TKey, TValue> dictionary_name = new Dictionary<TKey, TValue>();
Performing Different Operations on Dictionary
1. Adding Elements
- Add(): This method to add key/value pairs in your Dictionary.
- Collection-Initializer: We can also use a collection initializer to add elements to the dictionary.
- Using Indexers: We can directly add the elements by indexes.
// Using Add method
Dictionary<int, string> dict= new Dictionary<int, string>();
dict.Add(1, "One");// Using Collection Initializer
Dictionary<int, string> dict = new Dictionary<int, string>{
{ 1, "One" },
{ 2, "Two" }
};// Using Indexers
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "One";
dict[2] = "Two";
2. Accessing Elements
The key-value pair of the Dictionary is accessed using three different ways:
Using For Loop: We can use a for loop to access the key-value pairs of the Dictionary.
for (int x = 0; x < dict.Count; x++){
Console.WriteLine("{0} and {1}", dict.Keys.ElementAt(x), dict[dict.Keys.ElementAt(x)]);
}
Using Index: We can access individual key-value pairs of the Dictionary by using its index value. We can specify the key in the index to get the value from the given dictionary, no need to specify the index. The indexer always takes the key as a parameter
Console.WriteLine("Value is:{0}", dict[1]);
Console.WriteLine("Value is:{0}", dict[2]);
Note: If the given key is not available in the dictionary, then it gives KeyNotFoundException.
Using foreach loop:
foreach (var pair in dict)
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
Example: Creating and Displaying a Dictionary with Add()
using System;
using System.Collections.Generic;
class Geeks{
static public void Main(){
// Creating a dictionary using Dictionary<TKey,TValue> class
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-Value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Displaying the dictionary
foreach (KeyValuePair<int, string> ele in dict){
Console.WriteLine("key: {0} and value: {1}", ele.Key, ele.Value);
}
}
}
Output
key: 1 and value: Welcome key: 2 and value: to key: 3 and value: GeeksforGeeks
3. Removing Elements
In the Dictionary, we are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements that are:
- Clear: This method removes all keys and values from the Dictionary<TKey, TValue>.
- Remove: This method removes the value with the specified key from the Dictionary<TKey, TValue>.
Example:
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating a dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Before Remove() method
foreach (KeyValuePair<int, string> ele in dict){
Console.WriteLine("key: {0}, Value: {1}", ele.Key, ele.Value);
}
// Remove a key-value pair
dict.Remove(1);
Console.WriteLine("\nAfter Remove() method:");
foreach (KeyValuePair<int, string> ele in dict){
Console.WriteLine("key: {0}, Value: {1}", ele.Key, ele.Value);
}
}
}
Output
key: 1, Value: Welcome key: 2, Value: to key: 3, Value: GeeksforGeeks After Remove() method: key: 2, Value: to key: 3, Value: GeeksforGeeks
4. Checking Element
In Dictionary, we can check whether the given key or value is present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods which are:
- ContainsKey: This method is used to check whether the Dictionary<TKey, TValue> contains the specified key.
- ContainsValue: This method is used to check whether the Dictionary<TKey, TValue> contains a specific value.
Example:
using System;
using System.Collections.Generic;
class Geeks{
static public void Main(){
// Creating a dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Using ContainsKey() to check if the key exists
if (dict.ContainsKey(1))
Console.WriteLine("Key is found...!!");
else
Console.WriteLine("Key is not found...!!");
// Using ContainsValue() to check if the value exists
if (dict.ContainsValue("to"))
Console.WriteLine("Value is found...!!");
else
Console.WriteLine("Value is not found...!!");
}
}
Output
Key is found...!! Value is found...!!