Implementing the LINQ OrderBy Operator

linq orderbyLINQ (Language Integrated Query) is Microsoft’s latest data access technology. LINQ is an alternative to SQL (Structured Query Language) and helps developers avoid complexities that come with ordinary SQL. LINQ is integrated into .NET language, so it can use all the language features such as type safety and intelli-sense (if implemented inside an IDE.) LINQ contains operator for almost every SQL counterpart. One such operator is the LINQ OrderBy operator, which performs ordering of elements in a collection. The OrderBy operator runs a sorting algorithm internally and returns a sorted list of elements based on the type of OrderBy operator. OrderBy operator can be implemented on both generic and non-generic collections.

Interested in learning more about LINQ? Take this course

A basic LINQ OrderBy example

The following example demonstrates the how OrderBy operator can be used to alphabetically sort a list of strings:

List<string> countries = new List<string> {"USA", "CANADA", "AUSTRALIA", "ENGLAND","CHINA", "RUSSIA"};

 

IEnumerable<string> orderedcon = countries.OrderBy(n => n);

 

foreach(string country in orderedcon)

{

Console.WriteLine(country);

}

In the above example, a List collection of type string, named countries, has been instantiated and names of some random countries have been added in it. Next, OrderBy operator has been called on the countries collection in fluent syntax. In LINQ fluent syntax, a lambda expression or predicate is passed to a LINQ operator.

In this example, a predicate has been passed that order the element in the countries collection in the default order. By default, OrderBy operator orders list of string type elements alphabetically. The output would display all the elements in the countries collection alphabetically e.g. AUSTRALIA would be displayed on top, then CANADA, CHINA and so on.

LINQ OrderBy Element Length

The elements of a string type collection can be sorted based on its length. For this purpose, a slight change has to be made in the predicate passed to OrderBy operator in the last example. Change the following line of code in the last example and the elements displayed would be in ascending order of their length:

IEnumerable<string> orderedcon = countries.OrderByDescending(n => n.Length);

Here, the lambda expression denotes that OrderBy elements based on the length of each element. Now, the elements would be displayed in the order of their length, starting from the smallest element e.g USA, CHINA, CANADA and so on.

For more C# tutorials, check out this course

Implementing LINQ OrderBy on numbers collection

Implementing LINQ OrdetBy operator on numbers collection is similar to implementing it on string collection. The following example demonstrates how OrderBy operator can be used to order collection of some random numbers alphabetically.

int[] numbers = { 78, 4, 7, 2, 58, 62, 15, 46, 27 };

 

IEnumerable<int> orderednum = numbers.OrderBy(n => n);

 

foreach(int number in orderednum)

{

Console.WriteLine(number);

}

In the above example, an integer type array “numbers” has been instantiated with some random numbers and then the OrderBy operator has been called on the numbers array in the same way as it was called on the countries collection in the last example. The OrderBy operator would return collection of integers sorted in ascending order.

LINQ OrderBy on custom type collections

OrderBy operator can also be used to order collections containing custom types. In such cases OrderBy operator orders the collection based on a particular attribute of the type. Suppose there is a custom type Person. The definition of the Person class is as follows:

class Person

{

public string name;

public int age;

public DateTime dob;

 

public Person(string name, int age, DateTime dob)

{

this.name = name;

this.age = age;

this.dob = dob;

}

}

Any collection containing the objects of Person class can be ordered with respect to the Person name, age or dob (Date of birth). In the following example, a List collection contains person type items. This collection is being ordered by the name of the Person.

Person p1 = new Person("Adam", 22, new DateTime(1992, 2, 5));

Person p2 = new Person("Tori", 19, new DateTime(1995, 10, 6));

Person p3 = new Person("James", 29, new DateTime(1985, 11, 2));

Person p4 = new Person("Sofi", 24, new DateTime(1990, 4, 10));

List<Person> personlist = new List<Person> { p1,p2,p3,p4};

IEnumerable<Person> orderedpersons = personlist.OrderBy(p => p.name);

foreach (Person p in orderedpersons)

{

Console.WriteLine(p.name + " "+ p.age +" "+p.dob.ToString("d MMM, yyyy"));

}

In the above example, 4 objects of Person type have been instantiated and added to personlist collection. Then, the OrderBy operator has been called on the personlist. The predicate passed to OrderBy operator “p => p.name”, orders each Person object in the personlist collection in the alphabetical order of the names. Therefore, if the particulars of Person objects in the personlist collection are printed on console, person with name Adams will be printed first, followed by James, Sofi and Tori respectively.

To order the items in the personlist collection by age, following change is required to be made in the above example:

orderedpersons = personlist.OrderBy(p => p.age);

Now the items in the personlist collection will be printed in the ascending order of the age of the item. The data of Tori would be displayed first since she is the youngest with age 19 and so on.

Similarly, to order items by date of birth, following line of code can be inserted in the above example:

orderedpersons = personlist.OrderBy(p => p.dob);

LINQ OrderByDescending

The LINQ OrderByDescending operator is used to order the elements in a collection in the reverse order of the default OrderBy operator. For instance, if OrderByDescending is called on personlist collection in the last example and then predicate “p => p.age” is passed to it, the items in personlist collection will be ordered in the reverse order of age. For example in the console output the data of James would be printed first, since it has maximum age (29) followed by Sofi with 24 and so on. The OrderByDescending is used in the application as follows:

orderedpersons = personlist.OrderByDescending(p => p.age);

OrderByAscending operator also exists which orders the items in a collection in ascending order which OrderBy operator does by default.

Want to learn more LINQ and C# concepts? Take a course at Udemy.com