Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform an OR of two LINQ IQueryables

I've got two 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()));
    }

I want to create another IQueryable which combines the two queries as an OR e.g

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

I'd rather avoid duplication of code so I want to reuse the existing queryables rather than rewriting a new lambda expression like Where(x=> x.Code.StartsWith.... || x.Name.Contains.....)

like image 420
reach4thelasers Avatar asked Dec 13 '25 15:12

reach4thelasers


2 Answers

You can probably .Union the results of the two together

public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
     return SearchByName(searchQuery).Union(SearchByCode(searchQuery))
}
like image 80
Oblivion2000 Avatar answered Dec 15 '25 05:12

Oblivion2000


Depending on what code you do want to be able to reuse, this could be an alternative way of doing it where you are not duplicating the inner workings of your query conditions:

    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)); 
    }
like image 22
Ulf Åkerstedt Avatar answered Dec 15 '25 04:12

Ulf Åkerstedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!