Additional Linq Options

I have a linq request. I have a set of parameters from the form I'm collecting, where I need to filter based on the fields that the user is looking 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-line field filters that I need to filter out, including long and boolean. They can be zeros if the user does not select anything. How to include them in the request.

+7
source share
2 answers

This is one of the best examples of why LINQ is so powerful - deferred execution. You can create a query in different phases, and only when the query is finally executed or resolved, an SQL statement will 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(); 
+16
source

If the request does not contain a specific field, you do not need to include it as part of the where clause:

 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 set predicates in such a way as to make sure that you have only those conditions that you really need.

+5
source

All Articles