views:

58

answers:

2

Hi folks,

how can the ThenBy be translated to Linq-To-Sql, please?

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

var movies = from m in _db.Movies
             orderby m.Category
             // What's the syntax for ThenBy?! 
             // thenby m.Name 
             select m;

When i try to do thenby m.Name, i get a compiler error.

+5  A: 
var movies = from m in _db.Movies
         orderby m.Category, m.Name
         select m;
jrotello
A: 

In addition to a simple comma separated list of expressions (which is translated to ThenBy method call), you can also specify the sorting order:

var q = from m in db.Movies
        orderby m.Category descending, m.Name ascending 
        select m

// Translates to:
db.Movies.OrderByDescending(...).ThenBy(...)

Another example:

var q = from m in db.Movies
        orderby m.Category, m.Name descending
        select m

// Translates to:
db.Movies.OrderBy(...).ThenByDescending(...)

The first element of the comma separated list is translated to either OrderBy or OrderByDescending (if you specify the descending keyword). Similarly, the next elements are translated to either ThenBy or ThenByDescending. You can also write ascending, but this is the default option, so it behaves in exactly the same way as if you didn't use it.

Tomas Petricek