// 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 ("Porterhouse Steak", "14 oz. steak marinated in our house marinade and seasoned to perfection");
dict.Add ("Roasted Duck", "Half duck roasted in a savory bourbon sauce and draped in fresh cherries");
dict.Add ("Cobb Salad", "Rabbit food covered with eggs and meat");
dict.Add ("French Onion Soup", "Giant crouton with brown stuff, cheese, and onions");
dict.Add ("Grilled Cheese", "An american classic, white american cheese grilled between two slices of toast");
dict.Add ("Lasagna", "How did this make it on the menu?");
dict.Add ("Taco Supreme", "Yo quiero Taco Bell!");
// 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 Porterhouse Steak " + dict.ContainsKey ("Porterhouse Steak"));
Console.WriteLine ("Contains key Roasted Duck " + dict.ContainsKey ("Roasted Duck"));
Console.WriteLine ("Contains key Jelly Beans " + dict.ContainsKey ("Jelly Beans"));
// 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.Write ("\nNumber of items in the dictionary: " + dict.Count);
}
}
}