C Sharp Dictionary

C# Dictionary<TKey, TValue>

The concept of the hashtable is used to store the values based on a key in a C# Dictionary<TKey, TValue> class. Found in the System.Collections.Generic namespace, the C# Dictionary<TKey, TValue> class contains unique keys only, thus the stored elements can be easily searched or removed using the key.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        Dictionary&lt;string, string&gt; countries = new Dictionary&lt;string, string&gt;();  
        countries.Add("1","Mexico");  
        countries.Add("2","Australia");  
        countries.Add("3","Japan");  
        countries.Add("4","Nepal");  
        countries.Add("5","Canada");  
 
        foreach (KeyValuePair&lt;string, string&gt; i in countries)  
        {  
            Console.WriteLine(i.Key+" "+ i.Value);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic Dictionary<TKey, TValue> class. The Add() method is used to store the elements and the for-each loop is used to iterate the elements. To get the key and value, we are using the KeyValuePair class.

 

Please follow and like us:
Content Protection by DMCA.com