Data Access has been discontinued. Please refer to this page for more information.

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 a fluent model based on the Northwind database.

The following code is the LINQ example.

using ( FluentModel dbContext = new FluentModel() )
   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 );
Using dbContext As New FluentModel()
 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
  Next name
 Next product
End Using

See Also