简体   繁体   中英

Why is this Linq Where Clause not filtering the results

I am new to Linq and MVC and it has taken a lot of searching and learning to get to this point.

I have the following method that successfully receives the parameter "code".

    public ActionResult GetIssueList(string code)
    {
        //dynamic fill of project code dropdown on selection of customer code drop down
        ProjectManager pm = new ProjectManager();

        var projectcodes = pm.SelectAllProjects();
        var projects = new List<Project>();

        foreach (var proj in projectcodes)
        {
            projects.Add(proj as Project);
        }
        return Json(projects.Where(x => x.CustomerCode == code).ToList());
    }

The data is being retrieved from the database but the where clause does not filter out data that is equal to the parameter.

Debug through execution and make sure that the items certainly do not have the CustomerCode of code . My question for you though is "are the items in projectcodes Project objects? if they are not, you cannot as cast them to Project , but instead must make new Projects with that code new Project(projectCode)

Also, everything you had written above could easily be re-written as one line of code. (you may have to do a .ToList<Project>() before the Where , but I don't know your types so I won't assume)

public ActionResult GetIssueList(string code)
{
    return Json(new ProjectManager()
        .SelectAllProjects()
        .Select(proj => proj as Project)
        .Where(proj => proj.CustomerCode == code)
        .ToList();
}

Edit : Place a breakpoint in your above method on the return statement, and check before the comparison happens if the items in the list have the expected CustomerCode.

There are too many unknowns here to answer more precisely, but to more easily debug step-by-step, I suggest you change the Where call to a traditional loop (and change it back once you found the problem, of course):

public ActionResult GetIssueList(string code)
{
    IEnumerable<Project> projects =
        new ProjectManager()
        .SelectAllProjects()
        .Cast<Project>();

    //this is replacement for Where call.
    //Debug breakpoint here step by step and look at the CustomerCode values
    //to find out why they are all added.
    List<Project> filtered = new List<Project>();
    foreach(Project p in projects)
    {
        if(p.CustomerCode == code)
            filtered.Add(p);
    }

    return Json(filtered);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM