且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ Where子句中的if条件

更新时间:2022-01-25 19:08:51

是的,您可以:

var query = someList.Where(a => a == "something");
if (condition)
{
    query = query.Where(b => b == "something else");
}
var result = query.ToList();

由于Where正在生成IQueryable,因此执行被推迟到本例中的ToList,这样您就可以将Where尽可能多地链接在一起,然后在通过所有操作之后才执行您的条件.

Because Where is producing an IQueryable, the execution is deferred until the ToList in my example so you can chain Wheres together as much as you want and then just execute it after you have passed all your conditions.