0

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 );
            }
        }
    }
Uthaiah
  • 1,283
  • 13
  • 14

2 Answers2

3

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();
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0
from emp in db.Employees
orderby colName
...

Wrong. colName is the same for every employee. It have to be something like emp.EmployeeName.

In your case, I think, you better to try Reflection to get actual values of specific column of specific employee. Smth like that:

order by emp.GetType().GetProperty("colName").GetValue(emp, null)

Ugly. Not sure it will work while value is not casted to it's actual type.

mazharenko
  • 565
  • 5
  • 11