Query Expression Syntax Examples: Grouping

 

The examples in this topic demonstrate how to use the GroupBy method to query the AdventureWorks Sales Model using query expression syntax. The AdventureWorks Sales model used in these examples is built from the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.

The examples in this topic use the following using/Imports statements:

[!CODE [DP L2E Examples#ImportsUsing](../CodeSnippet/VS_Snippets_Data/DP L2E Examples#importsusing)]

The following example returns Address objects grouped by postal code. The results are projected into an anonymous type.

[!CODE [DP L2E Examples#GroupBySimple3](../CodeSnippet/VS_Snippets_Data/DP L2E Examples#groupbysimple3)]

The following example returns Contact objects grouped by the first letter of the contact's last name. The results are also sorted by the first letter of last name and projected into an anonymous type.

[!CODE [DP L2E Examples#GroupBySimple2](../CodeSnippet/VS_Snippets_Data/DP L2E Examples#groupbysimple2)]

The following example returns SalesOrderHeader objects grouped by customer ID. The number of sales for each customer is also returned.

[!CODE [DP L2E Examples#GroupByCount](../CodeSnippet/VS_Snippets_Data/DP L2E Examples#groupbycount)]

Queries in LINQ to Entities

Show: