Time for action – one-to-many mapping

Here is the first problem:

Suppose, we have a List of names and we want to index them as per the first two letters of these names:

  1. Copy the following code snippet as a query to LINQPad:
    string[] firstNames = { "Samuel", "Jenny", "Joyace", "Sam" };
    var map = firstNames.ToLookup(c => c.Length);
    foreach (var m in map)
    {
      Console.WriteLine(m.Key);
      foreach (var n in m)
      {
        Console.WriteLine("--" + n);
      }
    }
  2. Run the query and you should get the following output:
    Time for action – one-to-many mapping

What just happened?

ToLookup() creates what you can imagine as a one-to-many Dictionary.

The Lambda expression c => c.Length describes the key to be used for the ...

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.