使用逻辑运算符 &&|| 过滤列表的方法



我有一个想要过滤的广告列表。广告只有一个内容分级:G、PG、PG13 或 R。现在,我有一个方法,如果我只指定一个内容评级,则可以过滤列表。例如,如果我将"G"传递到我的方法中,我会在列表中返回只有"G"内容评级的项目。

如果我提供两个内容评级,如"G"和"PG",

该方法不会返回任何内容,因为它正在寻找内容评级为"G"和"PG"的广告,并且此类广告不存在,因为只有一个内容评级与每个广告相关联。

我想重写我的方法,以便如果我传入两个内容评级,比如"G"和"PG",它将返回具有"G"或"PG"的广告列表。

这是我的方法中需要解决的部分:

adList = adList.Where(ad => ad.IsG == filter.ContentRatings.IsG
        && ad.IsPG == filter.ContentRatings.IsPG
        && ad.IsPG13 == filter.ContentRatings.IsPG13
        && ad.IsR == filter.ContentRatings.IsR);

编辑:过滤器是一个类,广告。是PG和过滤器。ContentRatings.IsG (IsPG13, IsR, IsG) 是布尔值。如果您想知道,这是行不通的。

adList = adList.Where(ad => ad.IsG == filter.ContentRatings.IsG
        || ad.IsPG == filter.ContentRatings.IsPG
        || ad.IsPG13 == filter.ContentRatings.IsPG13
        || ad.IsR == filter.ContentRatings.IsR);

问题是,您检查了所有值,而这些值只应检查过滤器设置为 true 的广告值。

也许一些代码会让它更清楚:

adList = adList.Where(ad => 
           filter.ContentRatings.IsG && ad.IsG
        || filter.ContentRatings.IsPG && ad.IsPG
        || filter.ContentRatings.IsPG13 && ad.IsPG13
        || filter.ContentRatings.IsR && ad.IsR);

据我所知&&是在||之前评估的

然后你应该使用 or 运算符 || 而不是 && 运算符。 使用 &&&检查来确保左操作数和右操作数都为真。 换句话说,您的语句将只返回所有四个条件都为真的值。

最新更新