LINQ: GroupBy – “The Wonderland”

I was going through the document on LINQ Project Overview then got interested to an example there at page 14. The amazing feature of GroupBy, programming will become the communication language one I am sure. We will have lingo, dialects, accent etc. I am excited to share the logic mentioned there (commented for better understanding)

 Assume that you have an array containing the names. You are not sure the length of the names. You have given assignment to provide output that will show the names with equal length together. Hummm LINQ the easy approach of life,

using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

namespace LINQConsoleApplication1_Oct10

{

    class Program

    {

        static void Main(string[] args)

        {

            //Declare the String Array

  string[] names = {"Albert", "Burke", "Connor", "David",

                "Everett", "Frank", "George", "Harris"};

            //Defining the GroupBy logic (here it is lengthwise)

            var groups = names.GroupBy(s => s.Length);

          

            //Iterate through the collection created by the Grouping

            foreach(IGrouping<int, string> group in groups)

            {

                //Branch on the condition decided

                Console.WriteLine("Strings of Length {0}", group.Key);

                //Actual results

                foreach(string value in group)

                    Console.WriteLine(" {0}", value);

            }

            Console.ReadKey();

        }

    }

}

Output will look like

Strings of Length 6

 Albert

 Connor

 George

 Harris

Strings of Length 5

 Burke

 David

 Frank

Strings of Length 7

 Everett

Namoskar