How to make a dynamic order in LINQ?

advertisements

This question already has an answer here:

  • Dynamic LINQ OrderBy on IEnumerable<T> 16 answers

I am trying to get sort the data based on the user input. But the orderby clause is not executed in LINQ. How do i do that ?? Here is my code...

 [HttpGet]
    public JsonResult SortData(String colName , String sortorder)
    {
        using( EmployeeDB db = new EmployeeDB( ) )
        {
            if( sortorder == "desc" )
            {
                var JsonData = new
                {
                    Data = (from emp in db.Employees
                            orderby colName descending
                            select new
                            {
                                EId = emp.EId ,
                                EmployeeName = emp.EmployeeName
                            }).ToList( )
                };
                return Json( JsonData , JsonRequestBehavior.AllowGet );
            }
            else
            {
                var JsonData = new
                {
                    Data = (from emp in db.Employees
                            orderby colName
                            select new
                            {
                                EId = emp.EId ,
                                EmployeeName = emp.EmployeeName
                            }).ToList( )
                };
                return Json( JsonData , JsonRequestBehavior.AllowGet );
            }
        }
    }


You have to do something like this to make it work:

var colName= "EmployeeName";

var Column= typeof(Employee).GetProperty(colName);

Data = (from emp in db.Employees
        select new
        {
         EId = emp.EId ,
         EmployeeName = emp.EmployeeName
        })
        .AsEnumerable()
        .OrderBy(emp => Column.GetValue(emp, null))
        .ToList();

or:

 Data = (from emp in db.Employees
            select new
            {
             EId = emp.EId ,
             EmployeeName = emp.EmployeeName
            })
            .AsEnumerable()
            .OrderBy(i => i.GetType().GetProperty(colName).GetValue(i, null))
            .ToList();