Search code examples
c#linqc#-4.0lambdaexpression-trees

dynamic sort in linq


please consider this scenario:

I have a list of a class with about 50 fields.I want to have a Combobox that user can select according to what field list will sort.For example if user select "F1" list sort according to "F1".

I don't want to sort with if-else for every fields.I see this topic :

Sorting a gridview when databinding a collection or list of objects

but I can't use of it's answer. How I can use Expression Tree for this purpose?

thanks

Edit 1) :

According to dear @Thom Smith answer I wrote this code:

 using (NorthwindModel1.NorthwindEntities2 ent = new NorthwindModel1.NorthwindEntities2())
    {
        var query = from o in ent.Orders
                    where o.OrderID < 10257
                    select o;

        query.OrderBy("CustomerID", SortDirection.Ascending);

        GridView1.DataSource = query;
        GridView1.DataBind();
    }

but it was not sorted. if I wrote that code in this way:

GridView1.DataSource = query.OrderBy(o=>o.CustomerID);

it being sort. where is the problem?


Solution

  • OrderBy does not do an in-place sort. It returns a sequence which when evaluated will be sorted. This is usually done lazily, meaning: until it is enumerated, it does nothing. Your current code simply discards this all-important return value. The fix is simple: catch the return value:

    query = query.OrderBy("CustomerID", SortDirection.Ascending);
    

    Note: similarly, applying "Where" doesn't filter the existing data: it returns a sequence that when enumerated is filtered. So if you were filtering you'd have the similar:

    query = query.Where(...);