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:

1
2
3
4
5
6
// e.g. name and birth date
var people = new Dictionary<string, DateTime>
{
    { "John", new DateTime(2000, 1, 1) },
    { "Jane", new DateTime(2000, 1, 2) }
};

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:

1
2
3
4
foreach (var person in people)
{
    Console.WriteLine($"Name: {person.Key} Birth: {person.Value}");
}

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:

1
2
3
4
5
6
7
8
9
foreach (var name in people.Keys)
{
    Console.WriteLine($"Name: {name}");
}

foreach (var birth in people.Values)
{
    Console.WriteLine($"Birth: {birth}");
}

You can use Linq to filter entries:

1
2
3
4
foreach (var person in people.Where(i => i.Value.Year >= 2000))
{
    Console.WriteLine($"Name: {person.Key} Birth: {person.Value}");
}

Or you can transform/project it to some other data structures:

1
2
3
4
foreach (var username in people.Select(i => $"{i.Key}{i.Value.Year}"))
{
    Console.WriteLine($"Username : {username}");
}

That’s it.