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);}
Subscribe for Free
Want to stay ahead of the curve? Subscribe now to receive the latest updates, actionable insights, and thought-provoking ideas around business, technology, and leadership straight to your inbox.