开发者

handling empty strings using linq

开发者 https://www.devze.com 2023-04-12 11:30 出处:网络
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.Shou

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&g开发者_JAVA技巧t; 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".


How about something like this:

if (!string.IsNullOrWhiteSpace(jobNumber)) return _context.Jobs.Where(j => j.JobNumber.Contains(jobNumber));
if (!string.IsNullOrWhiteSpace(jobName)) return _context.Jobs.Where(j => j.JobName.Contains(jobName));
if (!string.IsNullOrWhiteSpace(projectDirectorName)) return _context.Jobs.Where(j => j.ProjectDirectorFullName.Contains(projectDirectorName));
if (!string.IsNullOrWhiteSpace(groupName)) return _context.Jobs.Where(j => j.GroupName.Contains(groupName));
else throw new ArgumentException ("No arguments specified");

Or something that reads better:

if (!string.IsNullOrWhiteSpace(jobNumber)) return FilterJobsByNumber(jobNumber);
if (!string.IsNullOrWhiteSpace(jobName)) return FilterJobsByName(jobName);
if (!string.IsNullOrWhiteSpace(projectDirectorName)) return FilterJobsByDirector(projectDirectorName);
if (!string.IsNullOrWhiteSpace(groupName)) return FilterJobsByGroupName(groupName);
else throw new ArgumentException ("No arguments specified");

For suitably defined FilterJobsByNumber etc.


Maybe it can helps.

    public IEnumerable<Job> GetJobs(string jobNumber, string jobName, string projectDirectorName, string projectManagerName, string groupName) {
    return this._context.Jobs.Where(
        j => (j == null || j.JobNumber.Contains(jobNumber)) ||
             (j == null || j.JobName.Contains(jobName));
}


You can try to use

string.IsNullOrWhiteSpace(yourString);  // .NET 4.0

OR

string.IsNullOrEmpty(yourString);

And if it is true, return an empty collection.


It should be

String.IsNullOrWhitespace and Trim()

see my code

 NorthwindDataContext db= new NorthwindDataContext();
               db.Log = sw;
               var oList = db.Categories
                   .Where(j =>
                            ( string.IsNullOrWhiteSpace(txtName.Text) || j.CategoryName.StartsWith(txtName.Text.Trim()))
                            &&
                            (string.IsNullOrWhiteSpace(txtDescription.Text) || j.Description.StartsWith(txtDescription.Text.Trim()))   
                          )
                   .Select(p => new { Name = p.CategoryName ,Description =p.Description }).ToList();  


I think String.IsNullOrWhitespace check is the best.


Assuming that you have applied .Trim() on your search terms before getting into your this code block, modify the code as follows:

public IEnumerable<Job> GetJobs(string jobNumber, string jobName, string projectDirectorName, string projectManagerName, string groupName) {
        return this._context.Jobs.Where(
            j => (j.JobNumber.Contains(jobNumber) && jobNumber!="")  ||
                 (j.JobName.Contains(jobName) && jobName != "") ||
                 (j.ProjectDirectorFullName.Contains(projectDirectorName) 
                      && projectDirectorName != "") ||
                 (j.GroupName.Contains(groupName) && groupName!=""));
    }

The point here is that you don't need to add the if conditions on your search terms. You may have multiple fields for search and it would just work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消