Chris Dixon
Chris Dixon

Reputation: 9167

LINQ functions for checking if a string exists before entering it into query

I've currently got a query (psuedo code here!), such as:

var query = p.Companies.Any((a => a.Name != "" || a.Name.Contains(variable1) &&
                            (a => a.Description != "" || a.Description.Contains(variable2));

Now, obviously this is a simplified version of what I'm trying to do as there's many more fields for me to check, but the base of my answer is - can I create a function/expression that is built up in such a way that it only generates the SQL it needs to?

Such as:

Expression<Func<Company, bool>> companyQuery;
if(!String.IsNullOrEmpty(variable1)) {
   // build up my expression
}

// Pass expression through to query when finalized

Any ideas out there on this? Thanks!

Upvotes: 1

Views: 167

Answers (2)

lante
lante

Reputation: 7336

You can build your query on-demand with the IQueryable class, for example:

IQueryable<Company> query = p.Companies;

if (condition1)
{
    query = query.Where(expression1);
}

if (condition2)
{
    query = query.Where(expression2);
}

Upvotes: 1

Servy
Servy

Reputation: 203844

You probably don't need to. You can trust the database to optimize the query for you before executing it, so it's unlikely to be a problem.

That said, yes, you can do it, and it's not all that hard either. (If the expressions were combined with OR semantics it would be a bit more work though.

IQueryable<Company> query = p.Companies.AsQueryable();

if(!string.IsNullOrEmpty(variable1))
    query = query.Where(company => company.Name != "" || company.Name.Contains(variable1));

if(!string.IsNullOrEmpty(variable2))
    query = query.Where(company => company.Description != "" || company.Description .Contains(variable1));

bool result = query.Any();

This is a pattern I find being used a lot on advanced search screens. If they're searching on this field, filter on this field, if they're not filtering on this field, don't include it.

Upvotes: 5

Related Questions