繁体   English   中英

为什么此Linq Where子句不过滤结果

[英]Why is this Linq Where Clause not filtering the results

我是Linq和MVC的新手,为此花了很多时间进行搜索和学习。

我有以下方法可以成功接收参数“ 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());
    }

正在从数据库中检索数据,但是where子句不会过滤掉等于该参数的数据。

通过执行进行调试,并确保这些项目肯定没有codeCustomerCode 但是,我的问题是“项目代码中是否存在Project对象中的Project ?如果不是,则不能as cast它们强制转换为Project ,而必须使用该代码创建new Projects new Project(projectCode)

另外,您上面编写的所有内容都可以轻松地重新编写为一行代码。 (您可能必须在Where之前做一个.ToList<Project>() ,但是我不知道您的类型,所以我不作假设)

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

编辑 :在上面的方法中在return语句上放置一个断点,并在进行比较之前检查列表中的项目是否具有预期的CustomerCode。

这里有太多的未知因素需要更精确地回答,但是为了更轻松地逐步调试,我建议您将Where调用更改为传统循环(当然,一旦发现问题就将其改回):

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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