Iterating Through a Dictionary in C#

Iterating Through a Dictionary in C#

A Dictionary allows you to store items in a collection using a key/value paring. By storing your data this way, you get all of the functionality of a standard .NET Collection with the added benefits of Hashing.

I'm going to start off by showing you how to get data into a Dictionary. Then, I'll move on to how to access specific data entries. And, finally, I'll demonstrate two methods of iterating through the Dictionary. This should give you enough information to get started with Dictionaries if you've never seen them before, and hopefully, teach you something new if you are already familiar with them.

Inserting Into a Dictionary

First, let's get some data into our Dictionary by adding some of the hard workers of Dunder Mifflin.

Dictionary<int, Person> employees = new Dictionary<int, Person>();employees.Add(1000, new Person("Jim Halpert"));employees.Add(1001, new Person("Pam Halpert"));employees.Add(1002, new Person("Andy Bernard"));employees.Add(1003, new Person("Dwight Schrute"));employees.Add(1004, new Person("Michael Scott"));

Retrieving Data From a Dictionary

Now that we have our employees in memory, we can access them in near constant time (O(1)) by using their ID.

Person p = employees[1003];  //Select Dwight

Iterating Through a Dictionary

Finally, we can iterate through the Dictionary to print a list of all Dunder Mifflin employees.

foreach (KeyValuePair<int, Person> employee in employees) {   Console.WriteLine(employee.Value.Name);}

If you are using C# 3.0 or later, you can make use of the implicit type var.

foreach (var employee in employees) {   Console.WriteLine(employee.Value.Name);}
Robert Greiner

Robert Greiner

Professional optimist. Passionate about cultivating high-performing teams @ scale by integrating the timeless wisdom of the past with the marvel of today's emergent technology in a practical way.

View Comments
Next Post

Using Stopwatches and Timers in .NET

Previous Post

Creating a Fluid Two-Column Layout With a Single Fixed Width Column

Subscribe for free

Subscribe to my newsletter and get the latest posts delivered right to your inbox for free. I don't spam and your email won't be shared with third-parties.

Thanks for subscribing!

Check your inbox to confirm your subscription.

Please enter a valid email address!