views:

279

answers:

3

HI, i want to do this:

orderby = "Nome, Cognome desc";
var timb = time.Timbratures.Include("Anagrafica_Dipendente").Where(p => p.CodDipendente == 1);
            if(orderBy != "")
             timb = timb.OrderBy(orderBy);

Is there any method for pass a string parameter to Orderby

thanks

+3  A: 

Absolutely. You can use the Dynamic Query Library, found here:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

It lets you create order-by 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.

Mike Mooney
A: 

You need to use the LINQ Dynamic Query Library in order to pass parameters at runtime,

This will allow linq statements like

string orderedBy = "Description";
var query = (from p in products
            orderby(orderedBy)
            select p);
Nicholas Murray
A: 

Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>.

It allows you to pass in an IEntitySorter<T> into your service methods and use it like this:

public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
    using (var db = ContextFactory.CreateContext())
    {
        IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);

        return sortedList.ToArray();
    }
}

And you can create an EntitiySorter like this:

IEntitySorter<Person> sorter = EntitySorter<Person>
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Id);

Or like this:

var sorter = EntitySorter<Person>
     .OrderByDescending("Address.City")
     .ThenBy("Id");
Steven