Lambda or Linq method to search multiple parameters

c#, lambda, linq

Solution

If I understand correctly, you don't want to filter if the value of the parameters is 0? If so, two solutions:

Check if the parameter is equal to 0 in your condition:

var lstJobs = dx.GetAllJobs().Where(x => 
    (SecLink == 0 || x.SectorLink.Equals(SecLink))
    && (LocLink == 0 || x.LocationLink.Equals(LocLink))
    && (IndLink == 0 || x.IndustryLink.Equals(IndLink))
    && (VacLink == 0 || x.VacancyTypeLink.Equals(VacLink))
    && x.JobName.Contains(keyword)).ToList();

Linq goodness, dynamically construct your query:

    var query = dx.GetAllJobs().Where(x => x.JobName.Contains(keyword));

    if (SecLink != 0)
    {
        query = query.Where(x => x.SectorLink.Equals(SecLink));
    }

    if (LocLink != 0)
    {
        query = query.Where(x => x.LocationLink.Equals(LocLink));
    }

    if (IndLink != 0)
    {
        query = query.Where(x => x.IndustryLink.Equals(IndLink));
    }

    if (VacLink != 0)
    {
        query = query.Where(x => x.VacancyTypeLink.Equals(VacLink));
    }

    var lstJobs = query.ToList();

Problem

I have a List of Of Objects and id like to query the list with multiple parameters to whittle down the results on a search page. ``` int SecLink = (!string.IsNullOrEmpty(Request.QueryString["Sector"])) ? Convert.ToInt32(Request.QueryString["Sector"]) : 0; int LocLink = (!string.IsNullOrEmpty(Request.QueryString["Location"])) ? Convert.ToInt32(Request.QueryString["Location"]) : 0; int IndLink = (!string.IsNullOrEmpty(Request.QueryString["Industry"])) ? Convert.ToInt32(Request.QueryString["Industry"]) : 0; int VacLink = (!string.IsNullOrEmpty(Request.QueryString["Vacancy"])) ? Convert.ToInt32(Request.QueryString["Vacancy"]) : 0; string keyword = Request.QueryString["SearchTerm"]; var dx = new DataX(); var lstJobs = dx.GetAllJobs().Where(x => x.SectorLink.Equals(SecLink) && x.LocationLink.Equals(LocLink) && x.IndustryLink.Equals(IndLink) && x.VacancyTypeLink.Equals(VacLink) && x.JobName.Contains(keyword)).ToList(); if (lstJobs.Count > 0) { uiRptSearchJobs.DataSource = lstJobs; uiRptSearchJobs.DataBind(); uiLitSearchResults.Text = string.Format("<h4>Search result found {0} matches</h4>", lstJobs.Count); } ``` The search params may be '0' as not selected from the previous page, so the results should reflect his. This is the querystring im passing: `Default.aspx?section=search&Sector=4&Location=0&Industry=0&Vacancy=0&SearchTerm=` but as you can see they querystring will change with what the user selects from the previous page.

Original source