Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable.
The advantage of a Dictionary is, that it is a generic type. A dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing according to the need.
- 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
C#
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}");
}
}
}
OutputKey: 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 dictionary_name = new 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 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()
C#
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);
}
}
}
Outputkey: 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:
C#
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);
}
}
}
Outputkey: 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:
C#
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...!!");
}
}
OutputKey is found...!!
Value is found...!!
Which methods are used to check the existence of keys and values in a C# Dictionary?
-
ContainsKey() and ContainsValue()
-
-
ExistsKey() and ExistsValue()
-
CheckKey() and CheckValue()
Explanation:
In a Dictionary, ContainsKey() is used to check if a key exists, and ContainsValue() is used to check if a value exists.
Which of the following statements about Dictionary<TKey, TValue> is TRUE?
-
Dictionary allows duplicate keys
-
Dictionary maintains the insertion order
-
Dictionary provides fast lookup based on keys
-
Dictionary is in the System.Collections namespace
What happens if you try to access a key that does not exist in a C# Dictionary?
-
-
It throws a KeyNotFoundException
-
It returns default(TValue)
-
It creates a new entry with that key
Quiz Completed Successfully
Your Score : 2/3
Accuracy : 0%
Login to View Explanation
1/3
1/3
< Previous
Next >
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers