Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple "order by" in LINQ

I have two tables, movies and categories, and I want to get an ordered list by categoryID first and then by Name.

The movie table has three columns ID, Name and CategoryID. The category table has two columns ID and Name.

I tried something like the following, but it didn't work.

var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name }) 
like image 720
Sasha Avatar asked Nov 18 '08 13:11

Sasha


People also ask

What is OrderByDescending?

OrderBy. Sorts the elements in the collection based on specified fields in ascending or decending order. OrderByDescending. Sorts the collection based on specified fields in descending order. Only valid in method syntax.

How do I get data in descending order in Linq?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.


2 Answers

This should work for you:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name) 
like image 152
Nathan W Avatar answered Oct 05 '22 02:10

Nathan W


Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies               orderby row.Category, row.Name              select row; 

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies               orderby row.Category descending, row.Name              select row; 
like image 21
Scott Stafford Avatar answered Oct 05 '22 00:10

Scott Stafford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!