I have two tables, movies
and categories
, and I get an ordered list by categoryID first and then by Name.
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 an IComparer
. First you need to
implement an IComparer
for the Movie
class like this:
public class MovieComparer : IComparer
{
public int Compare(Movie x, Movie y)
{
if (x.CategoryId == y.CategoryId)
{
return x.Name.CompareTo(y.Name);
}
else
{
return x.CategoryId.CompareTo(y.CategoryId);
}
}
}
Then you can order the movies with the following syntax:
var movies = _db.Movies.OrderBy(item => item, new MovieComparer());
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 the MovieComparer
accordingly.