C Sharp Dictionary

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Dictionary<TKey, TValue>

C# Dictionary class uses the concept of hashtable. It stores values on the basis of key. It contains unique keys only. By the help of key, we can easily search or remove elements. It is found in System.Collections.Generic namespace.

# Dictionary<TKey, TValue> example

Let's see an example of generic Dictionary class that stores elements using Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair class to get key and value.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class DictionaryExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         Dictionary<stringstring> names = new Dictionary<stringstring>();  
  9.         names.Add("1","Sonoo");  
  10.         names.Add("2","Peter");  
  11.         names.Add("3","James");  
  12.         names.Add("4","Ratan");  
  13.         names.Add("5","Irfan");  
  14.   
  15.         foreach (KeyValuePair<stringstring> kv in names)  
  16.         {  
  17.             Console.WriteLine(kv.Key+" "+kv.Value);  
  18.         }  
  19.     }  
  20. }  

Output:

1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan