执行两个LINQ IQueryables的OR(Perform an OR of two LINQ

2019-09-17 02:29发布

我有两个IQueryables:

    public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => x.Code.StartsWith(searchQuery.ToUpper()));
    }

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => x.Name.ToLower().Contains(searchQuery.ToLower()));
    }

我想创建另一个IQueryable的它结合了两个查询作为或EG

    public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        // return SearchByName(searchQuery) OR SearchByCode(searchQuery)
    }

我宁愿避免重复代码,所以我想重新使用现有的queryables而不是重写一个新的lambda表达式像Where(x=> x.Code.StartsWith.... || x.Name.Contains.....)

Answer 1:

根据你想能够重用什么样的代码,这可能是做这件事,你不重复的查询条件的内部运作的另一种方式:

    private static Func<Counterparty, string, bool> CodeStartsWith = (x, searchQuery) => x.Code.StartsWith(searchQuery.ToUpper());

    private static Func<Counterparty, string, bool> NameContains = (x, searchQuery) => x.Name.Contains(searchQuery.ToLower());

    public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
    { 
        return queryable.Where(x => CodeStartsWith(x, searchQuery)); 
    }

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => NameContains(x, searchQuery)); 
    }

    public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => NameContains(x, searchQuery) || CodeStartsWith(x, searchQuery)); 
    }


Answer 2:

你也许可以.Union两个结果一起

public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
     return SearchByName(searchQuery).Union(SearchByCode(searchQuery))
}


文章来源: Perform an OR of two LINQ IQueryables