CSharp - Dictionary<TKey,TValue> Type


Dictionary implements both the generic and nongeneric IDictionary interfaces.


using System;
using System.Collections.Generic;
class MainClass/*from   www.  jav a2 s .  co m*/
   public static void Main(string[] args)
     var d = new Dictionary<string, int>();

     d.Add("One", 1);
     d["Two"] = 2;     // adds to dictionary because "two" not already present
     d["Two"] = 22;    // updates dictionary because "two" is now present
     d["Three"] = 3;

     Console.WriteLine (d["Two"]);                
     Console.WriteLine (d.ContainsKey ("One"));   
     Console.WriteLine (d.ContainsValue (3));     

     int val = 0;

     if (!d.TryGetValue ("onE", out val))
       Console.WriteLine ("No val");              

     // Three different ways to enumerate the dictionary:

     foreach (KeyValuePair<string, int> kv in d)          
       Console.WriteLine (kv.Key + "; " + kv.Value);      

     foreach (string s in d.Keys) 
        Console.WriteLine (s);
     foreach (int i in d.Values)