C# LINQ Sorting – OrderBy and ThenBy Operators

Updated on     Kisan Patel

The Sorting operator in LINQ arranges the elements of a sequence based on one or more attributs.

The different Sorting operators are the OrderBy, OrderByDescending, ThenBy, ThenByDescending, and Reverse clauses.

The OrderBy and OrderByDescending operators are used to sort the data. The OrderBy clause arranges the data in an ascending order, which is the default behaviour.

NorthwindEntities _db = new NorthwindEntities();
var Customers = from customer in _db.Customers
                    orderby customer.Country, customer.City
                        select customer;

Or

NorthwindEntities _db = new NorthwindEntities();
var Customers = _db.Customers.OrderBy(x => x.Country).ThenBy(x => x.City);
Note : If you want to order your data in the descending order, you need to use the OrderByDescending clause.

The following example shows you how to use the OrderBy and ThenBy clause in a LINQ query to sort the Customer.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
            NorthwindEntities _db = new NorthwindEntities();
            var Customers = _db.Customers.OrderBy(x => x.Country).ThenBy(x => x.City);

            foreach (var customer in Customers)
                Console.WriteLine(customer.City + " - " + customer.Country);
        }
    }
}

the output of the above C# program…

LINQ-OrderBy-example


C# LINQ

Leave a Reply