I have a search form with multiple inputs - first name, last name, company...
I would like to return entities based on user inputs, or if nothing is input, in the last name field for instance, return all last names.
I believe I should be using null-coalescing for this, just like "ISNULL" in t-sql...
contacts = contacts.Where(s => s.firstname.ToUpper().Contains(fNameSearch.ToUpper() ?? *)
The issue is that I don't know how to use a wildcard in this type of experession.
For instance, this returns everything that contains "test" in the firstname property if fNameSearch is null or white-space...
contacts = contacts.Where(s => s.firstname.ToUpper().Contains(fNameSearch.ToUpper() ?? "test")
but I want to be able to return everything, not just "test".
If you want to return everything, can't you place the condition before the query?
var contacts = /* construct your original query here */
if (fNameSearch != null)
contacts = contacts.Where(s => s.firstname.ToUpper().Contains(fNameSearch.ToUpper());
Edit: Per Steve's comment below, case-sensitivity depends on the database's collation (and is case-insensitive by default), so you can just run:
var contacts = /* construct your original query here */
if (fNameSearch != null)
contacts = contacts.Where(s => s.firstname.Contains(fNameSearch));
Edit2: If you have multiple inputs to check for, you can use the same approach compositionally:
var contacts = /* construct your original query here */
if (string.IsNullOrEmpty(fNameSearch) == false))
contacts = contacts.Where(s => s.firstname.Contains(fNameSearch));
if (string.IsNullOrEmpty(fSurnameSearch) == false))
contacts = contacts.Where(s => s.surname.Contains(fSurnameSearch));
if (string.IsNullOrEmpty(fCompanySearch) == false))
contacts = contacts.Where(s => s.company.Contains(fCompanySearch));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments