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

AI Rule #1 - Customer First

In 1985, Warren Buffett wisely said, "The first rule of investment is don't lose. And the second rule of investment is don't forget the first rule, and that's all the rules there are." Similarly, the first rule of AI investment is to

AI Rule #1 - Customer First
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