I have two tables, movies
and categories
, and I get an ordered list by categoryID first and then by Name.
The movie table has three columns, ID, Name, and CategoryID. The category table two has 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 })
I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:
This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.
This should work for you:
use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:
The following LINQ statements:
AND
produce the following SQL:
Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:
AND
produce the following SQL (Name and CategoryId are switched):
There is at least one more way to do this using LINQ, although not the easiest. You can do it by using the
OrberBy()
method that uses anIComparer
. First you need to implement anIComparer
for theMovie
class like this:Then you can order the movies with the following syntax:
If you need to switch the ordering to descending for one of the items just switch the x and y inside the
Compare()
method of theMovieComparer
accordingly.If use generic repository
else
Using non-lambda, query-syntax LINQ, you can do this:
[EDIT to address comment] To control the sort order, use the keywords
ascending
(which is the default and therefore not particularly useful) ordescending
, like so: