Search code examples
c#.netentity-frameworklinqdynamic-linq

How to Conditionally the column in LINQ OrderByDescending for OrderBy?


How to Conditionally sort the column using LINQ OrderBy Clause.

ex- I have a Property Filter.OrderBy and Filter.Order. In OrderBy could be many ex> Name, Address, City etc and Order will be ascending or descending but I am not sure how to sort it with conditional columns.

Please find the below code for reference:

IQueryable<Filter> query;

PropertyInfo prop = typeof(Filter).GetProperty(Filter.OrderBy);  

if (Filter.Order ==" Ascending"){
  query = query.OrderBy ( x = > prop.GetValue(x,null));
}
else if (Filter.Order ==" Descending"){
  query = query.OrderByDescending ( x = > prop.GetValue(x,null));
}

But query is failing. I am not sure what is the issue I can see the prop property using reflection but the expression prop.GetValue is not working.

Please help me on this.


Solution

  • You can use the library System.Linq.Dynamic.Core which supports dynamic querying, selecting and ordering.

    Example code:

    var q = new List<Person>
    {
        new Person{Name = "C", Age = 30 },
        new Person{Name = "A", Age = 7 },
        new Person{Name = "B", Age = 5 }
    }.AsQueryable();
    
    var x1 = q.OrderBy("Name asc");
    
    var a1 = q.OrderBy("Age desc");
    

    For a full working example, see dotnetfiddle