CSharp examples for Collection:Dictionary
Demonstrate using a Dictionary<TKey, TValue> collection class.
using System;// w w w . j a va 2 s. c om using System.Collections.Generic; class Program { static void Main(string[] args) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("C#", "cool"); dict.Add("C++", "tutorial"); dict.Add("VB", "wordy language"); dict.Add("Java", "not C#"); dict.Add("Fortran", "old"); dict.Add("Cobol", "older"); Console.WriteLine("Contains key C# " + dict.ContainsKey("C#")); Console.WriteLine("Contains key Ruby " + dict.ContainsKey("Ruby")); Console.WriteLine("\nContents of the dictionary:"); foreach (KeyValuePair<string, string> pair in dict) { Console.WriteLine("Key: " + pair.Key.PadRight(8) + "Value: " + pair.Value); } Dictionary<string, string>.KeyCollection keys = dict.Keys; foreach(string key in keys) { Console.WriteLine("Key: " + key); } Dictionary<string, string>.ValueCollection values = dict.Values; foreach (string value in values) { Console.WriteLine("Value: " + value); } Console.Write("\nNumber of items in the dictionary: " + dict.Count); } }