I have a linq statement that searches a number of fields based on user input from a form. Only 1 form field is required, thus I need to handle empty string values. Whats the best way to handle this. Should i check the length of the string and then null the relevant vars and then check this in my linq statement or can i do something in my linq statement. My method is below :-
public IEnumerable<Job> GetJobs(string jobNumber, string jobName, string projectDirectorName, string projectManagerName, string groupName) {
return this._context.Jobs.Where(
j => j.JobNumber.Contains(jobNumber) ||
j.JobName.Contains(jobName) ||
j.ProjectDirectorFullName.Contains(projectDirectorName) ||
j.GroupName.Contains(groupName));
}
You could use this:
public IEnumerable<Job> GetJobs(string jobNumber, string jobName, string projectDirectorName, string projectManagerName, string groupName) {
IQueryable<Job> query = this._context.Jobs;
if (!String.IsNullOrEmpty(jobNumber))
query = query.Where(j => j.JobNumber.Contains(jobNumber));
if (!String.IsNullOrEmpty(jobname))
query = query.Where(j => j.JobName.Contains(jobName));
// etc.
return query;
}
If this will query the database, then that database will only get queried when you iterate over the results of this method, not for each ".Where".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With