Time for action – grouping by length

We can change the indexing key to anything we like. For example, say we want to group names as per their length. Only the Lambda expression will need the following change, everything else will remain the same. However, to give the output a better view, I changed the way the group key is printed:

  1. Copy the following code snippet as a query to LINQPad:
    string[] names = {"Sam", "Samuel", "Samu", "Ravi", "Ratna", "Barsha"};
    var groups  = names.GroupBy(c => c.Length);
    foreach (var gr in groups)
      Console.WriteLine("Words of Length {0}", gr.Key);
      foreach (var p in gr)
      Console.WriteLine("----" + p);
  2. Run the query. You should get the following output:

This operator can also be used to project elements of the collection ...

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.