This time I’m going to give a few quick tips for dictionaries in C#.
Some basic points before we begin:
- Dictionary is an unordered data structure
- Dictionary maps keys to values
- Keys have to be unique
- Dictionary implements IEnumerable
Let’s start by creating a simple dictionary with some data:
Looping through dictionary is simple, since it implements IEnumerable all we have to do is to use foreach loop. Each dictionary item has Key and Value property:
Also, remember that dictionary is unordered, which means that you cannot expect it to return values in the same order every time. So when you loop it one more time it can print values in different order.
We iterated through dictionary entries, but we can also iterate throught dictionary Keys or Values only:
You can use Linq to filter entries:
Or you can transform/project it to some other data structures: