OrderBy

OrderBy (Ascending)

This is how you order customers by CompanyName in an ascending way:

List<Customer> customers =
    context.Customers
        .OrderBy(c => c.ContactName)
            .ToList();

OrderByDescending

To order customers in a descending way, use the OrderByDescending method:

List<Customer> customers =
    context.Customers
        .OrderByDescending(c => c.ContactName)
            .ToList();

OrderBy with other methods

You can use other LINQ methods inside the OrderBy and OrderByDescending methods. To get customers ordered by the total sum of Order Freight descending, use Sum method like this:

List<Customer> customers =
    context.Customers
        .OrderByDescending(c => c.Orders.Sum(o => o.Freight))
            .ToList();

More ordering

Once you have one ordering specified, you can add more through ThenBy and ThenByDescending methods.

ThenBy

List<Customer> customers =
    context.Customers
        .OrderBy(c => c.CompanyName)
        .ThenBy(c => c.ContactName)
        .ToList();

ThenByDescending

List<Customer> customers =
    context.Customers
        .OrderBy(c => c.CompanyName)
        .ThenByDescending(c => c.ContactName)
        .ToList();

Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] linqtutorial [dot] info


Advertisements :