在 C# 中使用 EF 查询中的多个 Where 子句

Multiple Where clauses in query using EF in C#

我有两个 IQueryable 查询:

IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true);
IQueryable<Ad> list2;

if(something == true)
{
    list2 = list1.Where(x=>x.TypeId == 2) 
    // is it going to be the same as query below?
    IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true && x.TypeId == 2)   
}

如果我想使用 OR (||) 运算符获取数据怎么办是相同的情况。

而且我相信在我想要迭代此查询之前,这将是一个数据库调用。正确的?

list2 = list1.Where(x=>x.TypeId == 2) 
// is it going to be the same as query below?
IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true && x.TypeId == 2)  

是的 - 它会是一样的。

is it going to be the same as query below?

and what if I would like to get a data using OR (||) operator is the same scenario.

这样做会节省很多资源:

IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated);
IQueryable<Ad> list2;

if(something == true)
{
    list2 = list1.Where(x=>x.TypeId == 2) 
}
else 
{
    list2 = db.Ads.Where(x=>x.isModerated  || x.TypeId == 2)  
}

但如果出于某种原因您不想那样做,您可以这样做:

list2 = list1.Union(db.Ads.Where(x=> x.TypeId == 2)) 

会给你同样的结果集

正如我所注意到的,您确实有一个带有名为 list1 的 where 子句的查询,如果您确实有相同的内容,您将添加另一个 where 子句,所以我认为我会采取更精简、更简单的方法。

IQueryable<Ad> list1 = db.Ads.Where(x => (x.isModerated == true) && (something != true || x.TypeId == 2));

List<Ad> fetchedAds = list1.ToList();