(C# ASP.NET Core LINQ) How to Sort Records

A result set can be sorted in ascending as well as descending order. It is even possible to perform a chained sorting by using "ThenBy" and "ThenByDescending" methods. Finally we discuss whether "OrderBy" should be before or after "Where".
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Our working set

Let us suppose our model is

[Table("DoctorProfile")]
public class DoctorProfile
{

  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.None)]
  public int ID { get; set; }

  // name of a doctor 
  public String Name { get; set; }

  // fees of a doctor 
  public int Fees { get; set; }
}

In the following discussion we have assumed that

  1. that we have already configured our database
  2. that our DbContext instance is _ctx
  3. that our DbSet<DoctorProfile> is called Doctors

Video Explanation

Please watch the following youtube video:

How to sort in ascending order

Let us suppose that we have to sort our records on the basis of ID starting with the smallest one - in ascending order.


// the following code selects 
// the records and then sorts  
// the selection by ID ascending 
var doctors = _ctx.Doctors
                  .Where(f => f.Fees > 300)
                  .OrderBy(r => r.ID)
                  .ToList();

How to sort in descending order

Let us suppose that we have to sort our records on the basis of ID starting with the largest one - in descending order.


// the following code selects 
// the records and then sorts  
// the selection by ID descending 
var doctors = _ctx.Doctors
                  .Where(f => f.Fees > 300)
                  .OrderByDescending(r => r.ID)
                  .ToList();

How to sort on multiple keys

Let us suppose that we have to sort our records on the basis of ID ascending, followed by fees descending.


// the following code selects 
// the records and then sorts  
// the selected records by ID 
// then sorts by fees descending 
var doctors = _ctx.Doctors
                  .Where(f => f.Fees > 300)
                  .OrderBy(r => r.ID)
                  .ThenByDescending(f => f.Fees)
                  .ToList();

OrderBy should be before or after Where?

If OrderBy is placed before Where, then the whole table is first sorted and then the where clause operates. It might be time consuming if millions of records have to be first sorted and then filtered.

If OrderBy is placed after Where, then selection/filtering is the first step, and sorting the second. Obviously, sorting takes place on a smaller set of records, and could, therefore be faster.

If you keep the above in mind then you can write an optimal code.


This Blog Post/Article "(C# ASP.NET Core LINQ) How to Sort Records" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.