c# - LINQ - 当值为 NULL 时排除过滤器

标签 c# linq linq-to-sql linq-to-entities

当有一个可以为 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/

相关文章:

c# - 从 Mastercard/VISA 借记卡/信用卡读取 EMV 数据

c# - 无法加载文件或程序集“Microsoft.IdentityModel.Protocols.WsFederation,

c# - 将 xmlns 属性添加到根元素

c# - linq to sql通过多个ID字段链接对象

c# - 如何为属性定义别名

c# - 为什么 FormsAuthentication.SetAuthCookie 在 IE 中不起作用

c# - NHibernate 不支持指定的方法

c# - LINQ - 按名称分组到 Dictionary<string, List<T>>

asp.net-mvc - 没有数据库/框架的Asp.net mvc模型

c# - EntityFramework Code First继承与自定义鉴别器