Ordering in LINQ

There are four operators that are used for ordering output sequence in linq. They are as follows:

  • OrderBy
  • ThenBy
  • OrderByDescending
  • ThenByDescending

Orderby and ThenBy

The OrderBy operator is used to sort the data in the ascending order according to the condition specified by the lambda expression. The ThenBy operator is used to further sort those items that equal in the sorted order specified by the previous OrderBy operator. OrderBy and ThenBy operators are used in conjunction with each other. Have a look at the following example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] cararray = { "BMW", "Ford", "Toyota", "Honda", "Mercedez", "Capri" };
            IEnumerable<string> sortedcars = cararray.OrderBy(c => c.Length).ThenBy(s=>s);

            foreach (string s in sortedcars)  Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a collection named cararray has been defined which contains names of different car companies. This collection is sorted by OrderBy operator according to length. This will sort the items according to the ascending order of their length. However, Honda and Capri have equal length i.e. 5. In such cases the item that comes first in the collection is printed first. However to print Capri first, i.e in the alphabetical order, the ThenBy operator is used and the lambda expression defines that sort the item alphabetically. In this case Capri shall be added before Honda.

OrderbyDescending and ThenByDescending

These operators are similar to OrderBy and ThenBy operators except they sort the items in the sequence in descending order. Have a look at their working example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] cararray = { "BMW", "Ford", "Toyota", "Honda", "Mercedez", "Capri" };
            IEnumerable<string> sortedcars = cararray.OrderByDescending(c => c.Length).ThenByDescending(s=>s);

            foreach (string s in sortedcars)   Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}

Download the code

<<< Joining in LINQLINQ Projection Operators >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .