Group by substring in CSharp

Description

The following code shows how to group by substring.

Example


     /*www  . j a  v  a2  s.  c o  m*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;


public class MainClass{

   public static void Main(string[] args){   
         String[] TestData = {"One", "Two", "Three", "Four",
                              "Five", "Six", "Seven", "Eight", 
                              "Nine", "Ten"};

         var ThisQuery = from ThisElement in TestData
                         group ThisElement 
                         by ThisElement.Substring(0, 1)
                         into Groups
                         orderby Groups.Key
                         select Groups;

         foreach (var ThisElement in ThisQuery)
         {
            Console.WriteLine(ThisElement.Key);
            foreach (String ThisText in ThisElement)
               Console.WriteLine(ThisText);
         }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    LINQ »




Operator
Select
Where
OrderBy
Group
Join
Let
LINQ