![]() |
VOOZH | about |
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.
Example 1: Creating and Displaying a Dictionary
Key: 1, Value: C# Key: 2, Value: Javascript Key: 3, Value: Dart
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>();
// 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";
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 Indexer: We can access individual key-value pairs of the Dictionary by using its key. 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()
key: 1 and value: Welcome key: 2 and value: to key: 3 and value: GeeksforGeeks
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:
Example:
key: 1, Value: Welcome key: 2, Value: to key: 3, Value: GeeksforGeeks After Remove() method: key: 2, Value: to key: 3, Value: GeeksforGeeks
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:
Example:
Key is found...!! Value is found...!!