Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0367 Enumerate the dictionary

using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Sample { public static void Main() { var d = new Dictionary<string, int>(); d.Add("One", 1); d["Two"] = 2; // adds to dictionary because "two" not already present d["Two"] = 4; // updates dictionary because "two" is now present d["Three"] = 3; foreach (KeyValuePair<string, int> kv in d) // One ; 1 Console.WriteLine(kv.Key + "; " + kv.Value); // Two ; 22 foreach (string s in d.Keys) Console.Write(s); // OneTwoThree foreach (int i in d.Values) Console.Write(i); // 1223 } } The output: One; 1 Two; 4 Three; 3 OneTwoThree143