从以下 LINQ 查询开始:
from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value1 == b.Value1 &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;
如何删除(在运行时)where 子句中的一个或多个条件以获得类似于以下的查询:
from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;
或者
from a in things
where
a.Name == b.Name &&
a.Value3 == b.Value3
select a;
最佳答案
与其尝试更改现有的 where 子句,不如将其重构为:
from a in things
where a.Id == b.Id
where a.Name == b.Name
where a.Value1 == b.Value1
where a.Value2 == b.Value2
where a.Value3 == b.Value3
select a;
然后变成:
things.Where(a => a.Id == b.Id)
.Where(a => a.Name == b.Name)
.Where(a => a.Value1 == b.Value1)
.Where(a => a.Value2 == b.Value2)
.Where(a => a.Value1 == b.Value3);
现在应该相当清楚如何继续 - 条件化对 Where 的调用:
IQueryable<Whatever> query = things;
if (useId) {
query = query.Where(a => a.Id == b.Id);
}
query = query.Where(a => a.Name == b.Name);
if (checkValue1) {
query = query.Where(a => a.Value1 == b.Value1);
}
// etc
关于.net - 有选择地从 LINQ 表达式树中的 where 子句中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/325725/