Kel*_*sey 40
是的你可以喜欢:
var query = someList.Where(a => a == "something");
if (condition)
{
query = query.Where(b => b == "something else");
}
var result = query.ToList();
Run Code Online (Sandbox Code Playgroud)
因为Where正在产生一个IQueryable,所以执行被推迟到ToList我的例子中,所以你可以根据需要链接Where在一起,然后在你通过所有条件后执行它.
log*_*al8 35
var query = someList.Where(a => (someCondition)? a == "something" : true);
Run Code Online (Sandbox Code Playgroud)
所以,如果'someCondition'为false,将跳过'Where'.
WhereIf在linq中使用扩展方法avaialbe
例
if (SearchControlMain.PostingID.HasValue)
query = query.Where(q => q.PostingID == SearchControlMain.PostingID);
Run Code Online (Sandbox Code Playgroud)
而不是上面去下面
query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);
Run Code Online (Sandbox Code Playgroud)