我创建了一个表达式来过滤Linq语句:
Expression<Func<Driver, bool>> expression = null;
根据操作参数的值进行定义:
switch (driver_type)
{
case "all": // remove any filters related to `driver_type`
expression = d => true;
break;
case "licensed":
expression = d => !(new string[] { "A", "B" }).Contains(d.DriverType);
break;
case "unlicensed":
expression = d => d.DriverType == "D";
break;
default:
expression = d => !(new string[] { "A", "B" }).Contains(d.DriverType);
break;
}
然后将其用于过滤Linq查询:
drivers = await (
from driver in _context.Drivers
where
(driver.Active == true)
&& expression <-- invalid
orderby driver.LastName, driver.FirstName
select driver
).ToListAsync();
正确的语法是什么?
顺便说一句,default
开关选项是否可以使用由licensed
选项生成的表达式?
答案 0 :(得分:2)
您需要将其作为lambda传递。为了使其更具可读性,您可以将整个表达式更改为使用lambda。
drivers = await _context.Drivers
.Where(driver => driver.Active)
.Where(expression)
.OrderBy(driver => driver.LastName)
.ThenBy(driver => driver.FirstName)
.ToListAsync();