.net - 有选择地从 LINQ 表达式树中的 where 子句中删除

标签 .net linq

从以下 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/

相关文章:

.net - 抓取标签之间的所有 html

c# - iTextSharp 删除线

linq - 在 Linq to SQL 中使用委托(delegate)进行投影

c# - 使用 Linq 抛出异常

linq - 使用 LINQ to SQL 从存储过程中获取多维结果

c# - 来自数据源的 String 类型的给定值无法转换为指定目标列的 float 类型

.net - 如何忽略 System.Data.SqlClient.SqlException : String or binary data would be truncated. 异常

C# 在不知道文件格式的情况下读取二进制文本文件

带有函数(x)的 VB.NET Linq 表达式未执行?

sql-server - 始终加密、LINQ 以及包含位置