Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling empty strings using linq

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));
    }
like image 860
Richard Banks Avatar asked Oct 10 '11 10:10

Richard Banks


1 Answers

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".

like image 100
Hans Kesting Avatar answered Nov 03 '22 00:11

Hans Kesting