Sorting data in queries

Most of the time, as you retrieve your data from the database, you need to present it in a certain order. This order can include one or more fields and can be ascending, going from the smallest to the largest value, or descending, going from the largest to the smallest. You will find the sorting query syntax quite familiar, if you are accustomed to writing SQL queries. The following example will sort the person data on the last and first names of a person in ascending order. We are also going to combine filtering with sorting to illustrate how these two concepts work together in a single query, as shown in the following code snippet:

var query = from person in context.People
            where person.IsActive
            orderby person.LastName, person.FirstName
            select person;
var methodQuery = context.People
    .Where(p => p.IsActive)
    .OrderBy(p => p.LastName)
    .ThenBy(p => p.FirstName);

The first query uses the query syntax and the second one uses the method syntax. If you want to sort by multiple fields, then instead of using the Order By clause for both fields, you will need to use the ThenBy operator for the method syntax. Here is how the queries look in VB.NET:

Dim query = From person In context.People
            Where person.IsActive
            Order By person.LastName, person.FirstName
            Select person
Dim methodQuery = context.People _
                    .Where(Function(p) p.IsActive) _
                    .OrderBy(Function(p) p.LastName) _
                    .ThenBy(Function(p) p.FirstName)

When the descending sort order is required, you will need to use OrderByDescending for the first field and ThenByDescending for subsequent fields in queries with the method syntax. If you are using the query syntax, you will need to follow the property name with the descending keyword. You are free to combine the descending and ascending orders in a single query, as shown in the following code snippet:

var query = from person in context.People
            where person.IsActive
            orderby person.LastName descending, person.FirstName descending
            select person;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175