Skip to content

Iterating Through a Dictionary in C#

Robert Greiner
Robert Greiner
1 min read

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);}
Please consider subscribing, it's free.
Technology

Robert Greiner Twitter

Professional optimist. I write a weekly newsletter for humans at the intersection of business, technology, leadership, and career growth.


Related Posts

Members Public

Navigating the Upside Down as a Technology Leader

Ideas for leading technology organizations with confidence and creativity.

Navigating the Upside Down as a Technology Leader
Members Public

Artist for a Day

The future of creative output is multiplied by AI.

Artist for a Day
Members Public

The Auto Industry's Cloud Awakening

Auto manufacturers are behind the cloud adoption curve but are well-positioned to unlock the future of mobility by building foundational capabilities across six key areas.

The Auto Industry's Cloud Awakening