Back to: LINQ Tutorial For Beginners and Professionals
LINQ OrderBy Method in C# with Examples
In this article, I am going to discuss the LINQ OrderBy Method in C# with Examples. Please read our previous article where we discussed the basics of LINQ Ordering Operators. As part of this article, we are going to discuss the following pointers which are related to the LINQ OrderBy method.
- What is Linq OrderBy Method?
- Example of Linq OrderBy Method using both Method and Query Syntax.
- How to use Linq OrderBy Method with Complex Type in C#?
- How to use the OrderBy method along with the Filtering method?
- How to Create and use Own Comparer with LINQ OrderBy Method in C#?
What is Linq OrderBy Method?
The Linq OrderBy method in C# is used to sort the data in Ascending Order. The most important point that you need to keep in mind is that this method is not going to change the data rather it is just going to change the order of the data. You can use the OrderBy method on any data type i.e. you can use character, string, decimal, integer, etc. There are two overloaded versions of this OrderBy Method available inside LINQ. They are as follows.
The one and only difference between these two overloaded versions are that the second overloaded version takes the IComparer parameter which basically compares the keys when we are creating our custom comparer. Let us understand the use of the LINQ OrderBy method in C# using both query syntax and method syntax.
LINQ OrderBy Method with Value Data Type in C#
Let us see an example to understand how the LINQ OrderBy Method works with Value Data Type using C#. In the below example, we have a collection of integer data. And then we sort the data in ascending order using the LINQ OrderBy method using both Method and Query Syntax.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<int> intList = new List<int>() { 10, 45, 35, 29, 100, 69, 58, 50 }; Console.WriteLine("Before Sorting : "); foreach (var item in intList) { Console.Write(item + " "); } //Sorting the data in Ascending Order //Using Method Syntax var MS = intList.OrderBy(num => num); //Using Query Syntax var QS = (from num in intList orderby num select num).ToList(); Console.WriteLine(); Console.WriteLine("After Sorting : "); foreach (var item in QS) { Console.Write(item + " "); } Console.ReadKey(); } } }
Now, run the application and you will get the following output.
LINQ OrderBy Method with String Data Type in C#
Let us see an example to understand how the LINQ OrderBy Method works with String Data Type using C#. In the below example, we have a collection of string names. We then sort the data in ascending order using the LINQ OrderBy method with both Method and Query syntax.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<string> stringList = new List<string>() { "Preety", "Tiwary", "Agrawal", "Priyanka", "Dewangan", "Hina","Kumar","Manoj", "Rout", "James"}; //Using Method Syntax var MS = stringList.OrderBy(name => name); //Using Query Syntax var QS = (from name in stringList orderby name ascending select name).ToList(); foreach (var item in MS) { Console.WriteLine(item + " "); } Console.ReadKey(); } } }
When you run the above code, you will get the following output.
Note: In the Query Syntax, while we are sorting the data in ascending order then the use of ascending operator is optional. That means if we are not specifying anything then by default it is ascending. So the following two statements are the same.
LINQ OrderBy Method with Complex Data Type in C#:
Let us see how the LINQ OrderBy Method works with Complex Data Types in C# with some Examples. We are going to work with the following Student class. So, create a class file with the name Student.cs and then copy and paste the following code into it. As you can see, we created the Student class with four properties such as ID, FirstName, LastName, and Brach. We then created one method i.e. GetAllStudents() which is going to return a list of students.
using System.Collections.Generic; namespace LINQDemo { public class Student { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Branch { get; set; } public static List<Student> GetAllStudents() { List<Student> listStudents = new List<Student>() { new Student{ID= 101,FirstName = "Preety",LastName = "Tiwary",Branch = "CSE"}, new Student{ID= 102,FirstName = "Preety",LastName = "Agrawal",Branch = "ETC"}, new Student{ID= 103,FirstName = "Priyanka",LastName = "Dewangan",Branch = "ETC"}, new Student{ID= 104,FirstName = "Hina",LastName = "Sharma",Branch = "ETC"}, new Student{ID= 105,FirstName = "Anugrag",LastName = "Mohanty",Branch = "CSE"}, new Student{ID= 106,FirstName = "Anurag",LastName = "Sharma",Branch = "CSE"}, new Student{ID= 107,FirstName = "Pranaya",LastName = "Kumar",Branch = "CSE"}, new Student{ID= 108,FirstName = "Manoj",LastName = "Kumar",Branch = "ETC"}, new Student{ID= 109,FirstName = "Pranaya",LastName = "Rout",Branch = "ETC"}, new Student{ID= 110,FirstName = "Saurav",LastName = "Rout",Branch = "CSE"} }; return listStudents; } } }
Now, we want to sort the student data based on the Branch of the Student in ascending order. To do so, modify the Main method of the Program class as follows. In the below example, we are Sorting the data in ascending order based on the student branch using LINQ OrderBy Method with both Method and Query Syntax.
using System.Linq; using System; namespace LINQDemo { class Program { static void Main(string[] args) { //Method Syntax var MS = Student.GetAllStudents().OrderBy(x => x.Branch).ToList(); //Query Syntax var QS = (from std in Student.GetAllStudents() orderby std.Branch select std); foreach (var student in MS) { Console.WriteLine(" Branch: " + student.Branch + ", Name :" + student.FirstName + " " + student.LastName ); } Console.ReadKey(); } } }
When you run the above code, you will get the following output.
Sorting with Filtering using LINQ
Now we need to fetch only the CSE branch students and then we need to sort the data based on the FirstName in Ascending order. The most important point that you need to remember is, you need to use the Where method before the OrderBy method. This is because it will first filter results and then it will sort the filtered result which will improve the performance of the application. The following example shows the above using LINQ OrderBy and Where Method with both Query and Method Syntax.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Method Syntax var MS = Student.GetAllStudents() .Where(std => std.Branch.ToUpper() == "CSE") .OrderBy(x => x.FirstName).ToList(); //Query Syntax var QS = (from std in Student.GetAllStudents() where std.Branch.ToUpper() == "CSE" orderby std.FirstName select std); foreach (var student in QS) { Console.WriteLine(" Branch: " + student.Branch + ", Name :" + student.FirstName + " " + student.LastName ); } Console.ReadKey(); } } }
When you run the above code, you will get the following output as expected.
How to Create and use Own Comparer with LINQ OrderBy Method in C#?
It is also possible to create and use our own Comparer with LINQ OrderBy Method. For this, we need to use the Second Overloaded version of the OrderBy Method which takes the IComparer parameter. For a better understanding, please have a look at the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { public class CaseInsensitiveComparer : IComparer<string> { public int Compare(string x, string y) { return string.Compare(x, y, true); } } public class MainClass { public static void Main() { CaseInsensitiveComparer caseInsensitiveComparer = new CaseInsensitiveComparer(); string[] Alphabets = { "a", "b", "c", "A", "B", "C"}; var SortedAlphabets = Alphabets.OrderBy(aplhabet => aplhabet, caseInsensitiveComparer); foreach (var item in SortedAlphabets) { Console.Write(item + " "); } Console.Read(); } } }
Output: a A b B c C
In the next article, I am going to discuss how to sort the data in descending order by using the LINQ OrderByDescending Method in C# with Examples. Here, in this article, I try to explain the need and use of the LINQ OrderBy Method in C# with Examples. I hope you enjoy this OrderBy Method in C# article.