How to do dynamic orderby in LINQ?
本问题已经有最佳答案,请猛点这里访问。
我正在尝试根据用户输入对数据进行排序。但是ORDERBY子句没有在LINQ中执行。我该怎么做??这是我的密码…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | [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 ); } } } |
您必须这样做才能使它工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
或:
1 2 3 4 5 6 7 8 9 | 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(); |
1 2 3 | from emp in db.Employees orderby colName ... |
错了。每个员工的
我认为,在您的案例中,您最好尝试反射,以获得特定员工的特定列的实际值。史密斯喜欢这样:
1 | order by emp.GetType().GetProperty("colName").GetValue(emp, null) |
丑陋的不确定它会在值未强制转换为实际类型时工作。