Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Method-Based Query Syntax Examples: Ordering

The examples in this topic demonstrate how to use the ThenBy method to query the AdventureWorks Sales Model using method-based query 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:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;



The following example in method-based query syntax uses OrderBy and ThenBy to return a list of contacts ordered by last name and then by first name.

using (AdventureWorksEntities context = new AdventureWorksEntities())
IQueryable<Contact> sortedContacts = context.Contacts
.OrderBy(c => c.LastName)
.ThenBy(c => c.FirstName);

Console.WriteLine("The list of contacts sorted by last name then by first name:");
foreach (Contact sortedContact in sortedContacts)
Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName);



The following example uses the OrderBy and ThenByDescending methods to first sort by list price, and then perform a descending sort of the product names.

using (AdventureWorksEntities context = new AdventureWorksEntities())
IOrderedQueryable<Product> query = context.Products
.OrderBy(product => product.ListPrice)
.ThenByDescending(product => product.Name);

foreach (Product product in query)
Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",

See Also

Build Date:

© 2015 Microsoft