42
1
using System;
2
using System.Linq;
3
4
using System.Collections.Generic;
5
6
public class Program
7
{
8
public static void Main()
9
{
10
var cities = new Dictionary<string, string>(){
11
{"UK", "London, Manchester, Birmingham"},
12
{"USA", "Chicago, New York, Washington"},
13
{"India", "Mumbai, New Delhi, Pune"}
14
};
15
16
Console.WriteLine(cities["UK"]); //prints value of UK key
17
Console.WriteLine(cities["USA"]);//prints value of USA key
18
//Console.WriteLine(cities["France"]); // run-time exception: Key does not exist
19
20
//use ContainsKey() to check for an unknown key
21
if(cities.ContainsKey("France")){
22
Console.WriteLine(cities["France"]);
23
}
24
25
//use TryGetValue() to get a value of unknown key
26
string result;
27
28
if(cities.TryGetValue("France", out result))
29
{
30
Console.WriteLine(result);
31
}
32
33
Console.WriteLine("---access elements using for loop---");
34
//use ElementAt() to retrieve key-value pair using index
35
for (int i = 0; i < cities.Count; i++)
36
{
37
Console.WriteLine("Key: {0}, Value: {1}",
38
cities.ElementAt(i).Key,
39
cities.ElementAt(i).Value);
40
}
41
}
42
}
Cached Result