Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq optional parameters

I have a linq query. I have a bunch of parameters from a form I collect where I need to filter based of fields the user is searching for.

IQueyable<Users> user = from user in edmxObject.Users
where user.FirstName.Contains(model.FirstName ?? user.FirstName)
&& user.UserName.Contains(model.UserName ?? user.UserName)

I have a few more non string field filters I need to filter including long and boolean. They could be nulls if the user does not select anything. How do I include them in the query.

like image 835
desiguy Avatar asked Apr 05 '12 15:04

desiguy


2 Answers

This is one of the best examples of why LINQ is so powerful - deferred execution. You can build up the query in different phases, and only when the query is finally executed or resolved will the SQL statement be generated:

var query = edmxObject.Users.AsQueryable<Users>();

if (! String.IsNullOrEmpty(model.FirstName)) {
    query = from user in query
            where user.FirstName.Contains(model.FirstName)
            select user;
}
if (! String.IsNullOrEmpty(model.UserName) {
    query = from user in query
            where user.UserName.Contains(model.UserName)
            select user;
}

// this will cause the query to execute get the materialized results
var result = query.ToList();
like image 180
Yuck Avatar answered Nov 18 '22 12:11

Yuck


If the query doesn't include a particular field, you don't need to include it as part of the where clause at all:

IQueyable<Users> user = from user in edmxObject.Users;

if (model.FirstName != null) 
    users = users.Where(user => user.FirstName.Contains(model.FirstName)

if (/* age is searched for */) 
    users = users.Where(user => user.Age == model.Age);

You can conditionally nest predicates this way to ensure you have only the conditions you really need.

like image 5
recursive Avatar answered Nov 18 '22 13:11

recursive