当有一个可以为 NULL 的可选参数(CountryId)时,我想看看是否有更好的方法来编写下面的查询
public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null)
{
return repository
.Queryable()
.Where(x => (countryId != null ? x.CountryId == countryId : true) && x.Name.Contains(searchCriteria))
.AsEnumerable();
}
理想情况下,当 CountryId 为 NULL 时,我想排除过滤器中的条件。
-艾伦-
最佳答案
public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null)
{
return repository
.Queryable()
.Where(x => (countryId == null) || (x.CountryId == countryId && x.Name.Contains(searchCriteria)).AsEnumerable();
}
关于c# - LINQ - 当值为 NULL 时排除过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277791/