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;

}

//Remove

if(cars.Remove("V132")){

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s