How can I do an OrderBy with a dynamic string parameter?

linq, sql-order-by

Solution

Absolutely. You can use the LINQ Dynamic Query Library, found on Scott Guthrie's blog. There's also an updated version available on CodePlex.

It lets you create `OrderBy` clauses, `Where` clauses, and just about everything else by passing in string parameters. It works great for creating generic code for sorting/filtering grids, etc.

var result = data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo asc");

var query = DbContext.Data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo ascending");

Problem

I want to do this: ``` var orderBy = "Nome, Cognome desc"; var timb = time.Timbratures.Include("Anagrafica_Dipendente") .Where(p => p.CodDipendente == 1); if(orderBy != "") timb = timb.OrderBy(orderBy); ``` Is there an `OrderBy` overload available that accepts a string parameter?

Original source

Related problems