一个关于三目运算符的多条件查询问题
whereCondition是一个字典,Key是条件,Value是对应的值,当Key存在的时候,如whereCondition.ContainsKey("Email")为true,Linq就会执行data.Email == Convert.ToString(whereCondition["Email"]),当Key不存在的时候,Linq居然不鸟我写的true……就是说,当表达式为true时,三目运算符有效,当false时,三目运算符冒号后面的就执行不成功了,我试过写where true是可以像拼接SQL语句时的where 1=1 and 后加N个条件那样用的。请问大家有没有简单点的方法实现这个多条件查询捏?
public DataTable GetList(Dictionary<string, object> whereCondition)
{
var db = new dbDataContext();
try
{
var models = from data in db.T_User
where (whereCondition.ContainsKey("Email") ? data.Email == Convert.ToString(whereCondition["Email"]) : true)
&& (whereCondition.ContainsKey("Password") ? data.Password == Convert.ToString(whereCondition["Password"]) : true)
select data;
if (models != null)
{
return models.ToDataTable(rec => new object[] { models });
}
else
{
return null;
}
}
catch
{
return null;
}
}
------最佳解决方案--------------------Try write like this:
var models = from data in db.T_User
select data;
if(whereCondition.ContainsKey("Email"))
{
models =models.Where(data=>data.Email == Convert.ToString(whereCondition["Email"]) );
}
if(whereCondition.ContainsKey("Password"))
{
models =models.Where(data=>data.Password == Convert.ToString(whereCondition["Password"]) );