The C# Dictionary<TKey, TValue> class implements a hashtable to store values based on unique keys. These keys enable efficient search and removal of elements within the collection. This class is situated within the System.Collections.Generic namespace.
C# Dictionary__PRESERVE_4__ example
Let's examine a sample Dictionary<TKey, TValue> class which stores items via the Add function and traverses through elements using a for-each loop. In this scenario, the KeyValuePair class is employed to access both the key and the value of each element.
Example
using System;
using System.Collections.Generic;
public class DictionaryExample
{
public static void Main(string[] args)
{
Dictionary<string, string> names = new Dictionary<string, string>();
names.Add("1","Sonoo");
names.Add("2","Peter");
names.Add("3","James");
names.Add("4","Ratan");
names.Add("5","Irfan");
foreach (KeyValuePair<string, string> kv in names)
{
Console.WriteLine(kv.Key+" "+kv.Value);
}
}
}
Output:
Output
1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan