如何在LINQ中进行动态命令?

时间:2014-06-04 11:26:13

标签: c# asp.net asp.net-mvc linq lambda

我试图根据用户输入对数据进行排序。但是orderby子句不在LINQ中执行。我怎么做 ?? 这是我的代码......

 [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 );
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

你必须做这样的事情才能让它发挥作用:

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();

或:

 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 :(得分:0)

from emp in db.Employees
orderby colName
...

错误。 colName对每位员工都是一样的。它必须类似于emp.EmployeeName

在您的情况下,我认为,您最好尝试使用Reflection来获取特定员工特定列的实际值。像这样的Smth:

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

难看。不确定它是否会起作用,而值不会被转换为它的实际类型。