Pinch
Pinch

Reputation: 4207

Best way to handle where clause in Lambda

I have the following lambda for a simple search page using MVC:

Name and PostedName are strings.

Results.where(a=>a.Name.Contains(PostedName)).ToList();

Thanks great when PostedName has a value (excellent filter), but when it is empty, I get bupkas (empty list).

I would ideally like my where clause to be ignored when empty string.

How can this be done?

Something ideally shorthand without ifs and elses and whatifs.

Thanks!

Upvotes: 0

Views: 839

Answers (3)

Larry
Larry

Reputation: 18041

I would suggest:

Results.Where(a => a.Name.Contains((PostedName ?? "").Trim())).ToList();

"ThisIsAString".Contains("") returns true.

In the case PostedName is null, it will be changed to "".

If there is leading and/or trailing blanks characters in PostedName, then they will be removed.

Upvotes: 0

Phil Sandler
Phil Sandler

Reputation: 28016

David's answer is correct, but if you want a shortcut you can create an extension method to simplify usage example (untested by me).

Upvotes: 0

David
David

Reputation: 218877

You can dynamically add the WHERE clause. Keep in mind that you're just building an expression tree with these clauses and it's not actually executed until, in this case, you call .ToList(). So you can do something like this:

var filteredResults = Results;
if (!string.IsNullOrWhitespace(PostedName))
    filteredResults = filteredResults.Where(a => a.Contains(PostedName));
filteredResults = filteredResults.ToList();

Depending on the types you may need to explicitly declare a type for filteredResults in order for that to compile.

If you want something a little more in-line, this may do the trick:

Results.Where(a => string.IsNullOrWhitespace(PostedName) || a.Contains(PostedName)).ToList();

I think it's less clear on the intent, though. The benefit of the first example is also that you can add more filters following the same structure, basically dynamically adding more WHERE clauses for other filter fields as needed.

Upvotes: 4

Related Questions