将有条件构建的SQL where子句转换为LINQ

所以我没有在这里看到一个真正回答这个问题的问题。 这是一个关于linq的新手问题,但我想知道是否可以将以下sql查询(使用C#构建)转换为linq查询:

public void DoSomeQuery(bool whereCriteria1, bool whereCriteria2) { string sqlQuery = "SELECT p.*"; string fromClause = " FROM person p"; string whereClause = " WHERE "; if (whereCriteria1) { fromClause += ", address a"; whereClause += " p.addressid = a.addressid and a.state = 'PA' and a.zip = '16127' " } if (whereCriteria2) { fromClause += ", color c"; whereClause += " p.favoritecolorid = c.colorid and c.name = 'blue'" } // arbitrarily many more criteria if blocks could be here sqlQuery += fromClause + whereClause; // do stuff to run the query } 

那有意义吗? 我有一堆bool变量让我知道要添加哪个where子句标准。 我想在linq中这样做,因为这很难看。

 var query = from p in persons select p; if (whereCriteria1) { query = from p in query join a in address on p.addressid equals a.addressid where a.state = 'PA' where a.zip = '16127' select p; } if (whereCriteria2) { query = from p in query join c in colors on p.favoritecolorid equals c.colorid where c.name = 'blue' select p; } 

您正在寻找在运行时构建的动态谓词。 这是一篇很好的CodeProject文章。

您可能也对此PredicateBuilder感兴趣。

当然,答案类似于我为这个问题提供的答案。 基本策略是定义“基本查询”,然后有条件地将where子句添加到查询中。