Using Multiple Order By Clause in LINQ and Lambda Expression (C#)

by Ginktage | Wednesday, Jan 9, 2013 | 436 views

The orderby keyword can be used in LINQ to retrieve the ordered list of records based on the specified field.

For example to order the list of movies , one might use the orderby as shown below in the LINQ query

var moviesLinq1 = (from m in movies
orderby m.Actor
select m).ToList();

How to use Multiple OrderBy Clause in LINQ and Lambda Expression?

In C# , the developers can specify the columns with the comma separator to define multiple order by clause .

Below is a sample example of the data to be ordered by where Movies contains the list of movie properties.

public class Movie
{
public string MovieName { get; set; }

public string Actor { get; set; }

public string Director { get; set; }

public string Boxoffice { get; set; }

}
public class Movies : List<Movie>
{

public Movies()

{

Add(new Movie { Actor = "Vijay", Director = "Murugadas", MovieName = "Thuppaki" });

Add(new Movie { Actor = "Ajith Kumar", Director = "Chakri", MovieName = "Billa 2" });

Add(new Movie { Actor = "Vijay", Director = "Shankar", MovieName = "Nanban" });

Add(new Movie { Actor = "Surya", Director = "KV Anand", MovieName = "Maatran" });

Add(new Movie { Actor = "Vijay", Director = "Jayam Raja", MovieName = "Velayutham" });

}

}

To use multiple orderby condition in LINQ , one can use the statement like the way shown below.

List<Movie> movies = new Movies();

var moviesLinq1 = (from m in movies

orderby m.Actor , m.MovieName

select m).ToList();

The same can be achieved via Lambda expression with the OrderBy and ThenBy methods like shown below.

List<Movie> movies = new Movies();

var moviesLamba1 = movies.OrderBy(m => m.Actor).ThenBy(m => m.MovieName).ToList();

If the developer wants to sort one of the columns by ascending order and other by descending . He/she can simply specify itas shown below.

// Using LINQ Query

var moviesLinq2 = (from m in movies

orderby m.Actor ascending, m.MovieName descending

select m).ToList();

// Using Lambda Expression

var moviesLamba2 = movies.OrderBy(m => m.Actor).ThenByDescending(m => m.MovieName).ToList();
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Like it? Share it!

1 Comment so far. Feel free to join this conversation.

    Leave A Response