How To Access Dictionary Elements?

Forums C#How To Access Dictionary Elements?
Staff asked 3 weeks ago

Answers (1)

Add Answer
Mustakim Khalifa Marked As Accepted
Staff answered 3 weeks ago

The Dictionary can be accessed by specifying a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.

var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}

Console.WriteLine(cities["UK"]); //prints value of UK key
Console.WriteLine(cities["USA"]);//prints value of USA key
//Console.WriteLine(cities["France"]); // run-time exception: Key does not exist

//use ContainsKey() to check for an unknown key

//use ElementAt() to retrieve key-value pair using index
for (int i = 0; i < cities.Count; i++)
Console.WriteLine("Key: {0}, Value: {1}",

I hope, this will help you.


Select Categories