// Sample Dictionary
using System;
using System.Collections.Generic;
namespace DictionaryExample
{
class Program
{
static void Main(string[] args)
{
// Create a dictionary in which both keys and values are strings.
Dictionary<string, string> dict = new Dictionary<string, string>();
// Add some items to the dictionary: each has a key and a value.
dict.Add ("Aprilia Rsv4", "An Aprilia made sport bike");
dict.Add ("Yamaha R1M", "Yamahas super sport bike");
dict.Add ("ZX10RR", "Kawasakis Sport bike with a more performance built motor");
dict.Add ("Ducati V4s", "Ducatis more track driven V4 model");
dict.Add ("Honda CBR Fireblade", "Hondas new sport bike");
dict.Add ("BMW S1000RR", "BMWs made sport bike");
dict.Add ("GSXR 1000", "Suzukis liter sport bike");
// See if the dictionary contains a particular key.
Console.WriteLine ("Use the ContainsKey method to see if a movies exists in your dictionary:");
Console.WriteLine ("Contains key Aprilia Rsv4 " + dict.ContainsKey ("Rudy"));
Console.WriteLine ("Contains key Yamaha R1M " + dict.ContainsKey ("Patton"));
Console.WriteLine ("Contains key Ducati V4s " + dict.ContainsKey ("State Fair"));
// Iterate the dictionary's contents with foreach.
// Note that you're iterating pairs of keys and values,
// using the KeyValuePair<T,U> type.
Console.WriteLine ("\nContents of the dictionary:");
foreach (KeyValuePair<string, string> pair in dict)
{
// Because the key is a string, you can use string methods
Console.WriteLine ("Key: " + pair.Key.PadRight(8) + " Value: " + pair.Value);
}
// List the keys, remember they are in no particular order.
Console.WriteLine ("\nJust the keys:");
// Dictionary<TKey, TValue>.KeyCollection is a collection of just the keys,
// in this case strings. So here's how to retrieve the keys:
Dictionary<string, string>.KeyCollection keys = dict.Keys;
foreach(string key in keys)
{
Console.WriteLine ("Key: " + key);
}
// List the values, which are in same order as key collection above.
Console.WriteLine ("\nJust the values:");
Dictionary<string, string>.ValueCollection values = dict.Values;
foreach (string value in values)
{
Console.WriteLine ("Value: " + value);
}
Console.WriteLine("\nContents of the dictionary sorted by keys:");
foreach (var pair in new SortedDictionary<string, string>(dict))
{
Console.WriteLine("Key: " + pair.Key.PadRight(20) + " Value: " + pair.Value);
}
Console.Write ("\nNumber of items in the dictionary: " + dict.Count);
}
}
}