日期:2014-05-20  浏览次数:20832 次

动态组成linq查询的方法
现在view中有三个dropdownlist供用户选择部门department,状态status,工种worktype查询出复合条件的人。用户可能选择其中一个或多个条件查询。
需要在controller里接收这三个参数,组成一句linq查出用户想选的人员,如何实现。
sql的话就比较简单
如果三个参数全空就
string sqlcmd=select * from users ;
如果不是全空,则
String sqlcmd=select * from users where
之后判定不为空的参数append到string后面组成sql语句。
linq的话不知道有没有简便的方法实现此功能。
------解决方案--------------------
public void Test(string department, string status, string worktype)
        {
            QueryContext query = new QueryContext();
            var q = from u in query.Users
                     select u;
            if (!string.IsNullOrEmpty(department))
            {
                q = q.Where(p => p.department== department);
            }
            if (!string.IsNullOrEmpty(status))
            {
                q = q.Where(p => p.status == status);
            }
            if (!string.IsNullOrEmpty(worktype))
            {
                q = q.Where(p => p.worktype== worktype);
            }
            q.ToList();  //上边的所有if,只有到此处才会执行
        }

state类型自己修改下,大概是这样
参考http://blog.csdn.net/q107770540/article/details/5724013