Group by the first letter of name Using LINQ


Group by the first letter of name Using LINQ

Program:

                              List<String> names = new List<string>()
{ "Elizabeth", "Mr Christian", "James Stephens",   
  "Neal Sussman","Richard E", "Peter Banes",
                "William Cook", "Matthew D","Mark Dennis",
"Mrs Camilla Harrison", "Robert","John Smith"};

var groupedNames = from n in names
                   group n by n[0] into g
                   orderby g.Key
                   select new { FirstChar = g.Key, Names = g };

foreach (var group in groupedNames)
{
Console.WriteLine(group.FirstChar);
foreach (var name in group.Names)
{
Console.WriteLine("\t" + name);
}
}
    
 Console.ReadLine();


OutPut: 

Comments

Popular posts from this blog

iframe vs embed vs object in HTML 5

Constructor in c#

What is the need of method overriding ???