Content deleted Content added
m →Haskell |
→C#: aligned with other examples. |
||
Line 55:
===C#===
<source lang=CSharp>
MessageBox.Show((string) ht["testKey"]);▼
dic.Add("J. Random Hacker", "553-1337");
</source>▼
// access an phone number and display it in a message box
<source lang=CSharp>▼
▲Dictionary<int, string> dic = new Dictionary<int, string>();
▲</source>
▲dic.Add(7, "Bond");
</source>▼
The dictionary can also be initialized with all entries during construction. This is called "object initialization".
▲<source lang=CSharp>
{
{"Sally Smart", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}
▲</source>
A foreach loop can enumerate through the entire collection. There is no guarantee of order. If order matters the programmer could choose to use a SortedDictionary or use a .Sort linq extension method.
<source lang=CSharp>
// loop through the collection and display each entry
▲Dictionary<int, string> = new Dictionary<int, string> {
foreach(KeyValuePair<string,string> kvp in dic)
▲ { 7, "Bond" }
{
};▼
MessageBox.Show(String.Format("Phone number for {0} is {1}", kvp.Key, kvp.Value);
</source>
|