Multiple "order by" in LINQ

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 })

这应该适合你:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)

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;

Add "new":

var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })

That works on my box. It does return something that can be used to sort. It returns an object with two values.

Similar, but different to sorting by a combined column, as follows.

var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))
链接地址: http://www.djcxy.com/p/5852.html

上一篇: 何时使用。首先以及何时使用.FirstOrDefault与LINQ?

下一篇: LINQ中的多个“order by”