Tag Archives: C# Dictionary

C# – Working with the Dictionary

Dictionary allows you to use a key to access a member of the collection.

Think: Webster’s dictionary… the word (key) then the definition (instance of a given type)

Key is anything that is meaningful in your system.

Key must be unique.

TKEY => type of the key

TValue => type of the value

Dictionary cars = new Dictionary();

cars.Add("V123", new Car{Make="BMW", Model="528i", Year=2010});

cars.Add("V132", new Car{Make="BMW", Model="575", Year=2015});

cars.Add("V321", new Car{Make="BMW", Model="533i", Year=2012});

cars.ElementAt(2).Key // returns V132

cars.Element.(2).Value // Return the Car object in the second position

//Better way to access Dictionary

Car v2;

if(cars.TryGetValue("V132", out v2){

result += v2.Year;




result += "Successfully removed car";