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";




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: