Multiple “order by” in LINQ

后端 未结 7 1709
小蘑菇
小蘑菇 2020-11-22 00:16

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

7条回答
  •  长情又很酷
    2020-11-22 00:36

    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.

提交回复
热议问题