Dictionary Collections And Initialization

Dictionary collections are similar to the other types of collection I’ve posted about. With the exception of a Dictionary collection uses a key of type for each collection entry. This makes it so you can look-up an item by its key. Again this code is small and not a part of any program. More of my notes as I went along teaching myself about this collection type. Gotta be honest I was liking how this worked.

Default.aspx Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DictionaryCollection
    public partial class Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            // Examples of using a collection instead of an array.
            string result = "";
            string searchResult = "";

            // Here I will show to use the Dictionary collection for the cars examples I've been using.
            // Notice the V1, V2, etc.., string key values for this.
            Dictionary<string, Car> cars = new Dictionary<string, Car>();
            cars.Add("V1", new Car { Make = "BMW", Model = "528i", Year = 2010, Color = "Black" });
            cars.Add("V2", new Car { Make = "BMW", Model = "745li", Year = 2005, Color = "Black" });
            cars.Add("V3", new Car { Make = "Ford", Model = "Escape", Year = 2008, Color = "White" });

            // Or you can do the above with a collection initializer.
            Dictionary<string, Car> cars = new Dictionary<string, Car>()
                { "V1", new Car { Make = "BMW", Model = "528i", Year = 2010, Color = "Black" } },
                { "V2", new Car { Make = "BMW", Model = "745li", Year = 2005, Color = "Black" } },
                { "V3", new Car { Make = "Ford", Model = "Escape", Year = 2008, Color = "White" } }

            // Here's how to remove an item from the Dictionary collection. Comment or un-comment to see this work.
            if (cars.Remove("V1"))
                result += "Successfully removed V1</br>";

            // Now to display it I'm using the same for loop as always with a little modification because
            // of the key value.
            for (int i = 0; i < cars.Count; i++)
                // Doing some string modification here. Yes I could use String.Format(). To lazy here. šŸ™‚
                result += "<h2>" + cars.ElementAt(i).Key + "</h2>" +        // This will display the key.
                    cars.ElementAt(i).Value.FormatDetailsForDisplay();      // This will display the car object.

            // Using an example of a Foreach loop to go thru the dictionary instead of a for loop.
            foreach (KeyValuePair<string, Car> car in cars)
                result += "<h2>" + car.Key + "</h2>" + car.Value.FormatDetailsForDisplay();

            // Doing the above is pretty standard and boring. Here's a way to grab a value based on the key.
            // Basically searching.
            Car v2;     // Create an object.
            if (cars.TryGetValue("V2", out v2))
                searchResult += "<h2>Search Results:</h2>";
                searchResult += v2.FormatDetailsForDisplay();

            resultLabel.Text = result;
            searchLabel.Text = searchResult;

    public class Car
        // Public properties
        public string Make { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }
        public string Color { get; set; }

        // Constructors
        public Car()
            this.Make = "Undefined";
            this.Model = "Undefined";
            this.Year = 1980;
            this.Color = "Undefined";

        // Public methods.
        public string FormatDetailsForDisplay()
            return String.Format("Make: {0} - Model: {1} - Year: {2} - Color: {3}</br>",
                Make, Model, Year, Color);


As you can see initializing a Dictionary collection is similar to a List type collection. The one exception is the use of key value type. In this case here I’m using a string as the key value type. My idea was that this is a pseudo VIN number of a car since that’s a universal number that can be used as a key. The key does need to be identical to the list entry. You can’t have another list entry with the same key otherwise exceptions are thrown.

Notice also that when you iterate thru a Dictionary list you have to do it differntly than you would a normla List collection. The simplest way I found was to use the KeyValuePair struct when performing a foreach loop.

I was also messing aaround with a simple search idea. I’m doing this by creating a Car object but not initializing it. Instead I’m using an If statement with a TryGetValue method using an out parameter. And I’m hardcoding in one of the key values from the Dictionary list to search thru. Simple in concept I know. However it shows how you can look for specific items in a Dictionary list rather than just iterating thru each time.

Leave a Reply

Please log in using one of these methods to post your comment:

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