Time for action – flattening a dictionary

Suppose, we have a dictionary such that each key has a list of values attached to them. Now, we want to project all the elements in a single collection:

  1. Copy the following code snippet as a query to LINQPad:
    Dictionary<string, List<string>> map = new Dictionary<string, List<string>>();
    map.Add("UK", new List<string>() { "Bermingham", "Bradford", "Liverpool" });
    map.Add("USA", new List<string>() { "NYC", "New Jersey", "Boston", "Buffalo" });
    var cities = map.SelectMany(c => c.Value).ToList();
    cities.Dump("All Cities");
  2. Run the query. You should see the following output:
    Time for action – flattening a dictionary

What just happened?

In this example, ...

Get .NET 4.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.