How to: Group Data

This topic shows how to group query results. The example returns a set of nested data records that contain the Product.ProductName column, grouped and sorted alphabetically by the first letter of Product.ProductName.

To run the code in this example, you need to create a new Telerik Data Access Domain Model based on the Northwind database.

The following code is the LINQ example.

C#


    using ( EntitiesModel dbContext = new EntitiesModel() )
    {
       var query = ( from product in dbContext.Products
                     group product by product.ProductName.Substring( 0, 1 ) into productGroup
                     select new
                     {
                         FirstLetter = productGroup.Key,
                         Names = productGroup
                     } ).OrderBy( letter => letter.FirstLetter );
       foreach ( var product in query )
       {
           Console.WriteLine( "Product names that start with the letter '{0}':",
               product.FirstLetter );
           foreach ( var name in product.Names )
           {
               Console.WriteLine( name.ProductName );
           }
       }
    }

VB


    Using dbContext As New EntitiesModel()
     Dim query = (
         From product In dbContext.Products
         Group product By GroupKey = product.ProductName.Substring(0, 1) Into productGroup = Group
         Select New With {Key .FirstLetter = GroupKey, Key .Names = productGroup}).OrderBy(Function(letter) letter.FirstLetter)
     For Each product In query
      Console.WriteLine("Product names that start with the letter '{0}':", product.FirstLetter)
      For Each name In product.Names
       Console.WriteLine(name.ProductName)
      Next name
     Next product
    End Using

See Also