3

我有两个 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 将这两个查询组合为 OR 例如

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

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

4

2 回答 2

5

您可能可以将两者的结果结合在一起

public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
     return SearchByName(searchQuery).Union(SearchByCode(searchQuery))
}
于 2012-05-08T14:54:41.333 回答
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)); 
    }
于 2012-05-08T18:01:20.477 回答