【问题标题】:c# List using where statementc# 使用 where 语句列出列表
【发布时间】:2013-04-28 14:22:00
【问题描述】:

我的应用程序是使用 Linq-to-Sql 的 asp.net MVC。我正在尝试使用以下内容来过滤视图。

我已经使用以下方法将过滤器添加到我的 SQL Server 视图中:

WHERE (dbo.Client.Recstatus IS NULL) OR (dbo.Client.Recstatus = 0)

当我在 SQL Server Management Studio 中运行它时,它运行良好,但是我仍然在我的应用程序中看到这些条目。

我尝试在我的存储库中再次过滤它:

List<vw_Client_info> searchResult = new List<vw_Client_info>().Where(c=> c.Recstatus != 1);

Recstatussmallint

我收到以下错误:

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?)

非常感谢您的帮助,在此先感谢。

【问题讨论】:

    标签: c# sql asp.net-mvc-3 filtering


    【解决方案1】:

    您似乎忘记在最后使用ToList() 方法。试试这个:

    List<vw_Client_info> searchResult = 
        new List<vw_Client_info>().Where(c=> c.Recstatus != 1).ToList();
    

    【讨论】:

    • 非常感谢侯赛因,我没有收到错误。知道为什么如果我在 Sql 中过滤了我的视图,数据仍然显示!再次感谢。
    • @user373721 不确定我是否理解您的评论。
    • 我想弄清楚,如果我在 sql 视图中有过滤器,以及何时运行它;它删除了所有等于 1 的条目。但是在我的 MVC 表中,这些等于 1 的条目仍然显示。谢谢
    【解决方案2】:

    两个问题

    1. new List&lt;vw_Client_info&gt;() 是新列表,没有数据
    2. 您必须在语句末尾调用.ToList()

    你可以试试下面的方法

    using (YourDatacontext context= new YourDatacontext(connStr))
    {
        List<vw_Client_info> searchResult = 
              context.vw_Client_infos.Where(c=> c.Recstatus != 1).ToList();
    }
    

    【讨论】:

    • 感谢大家的热心和快速支持
    【解决方案3】:

    这是因为您从 Select 中返回了一个匿名类型,并且您试图将其存储在 List&lt;vw_Client_info&gt; 中。投影总是创建匿名类型。 这样您就可以将其存储在IEnumerable 或在尾部使用ToList()

    【讨论】:

      【解决方案4】:

      包括Where 在内的可枚举方法不返回 List,而是返回 IEnumerable

      所以你可以修改你的代码

      IEnumerable<vw_Client_info> searchResult = 
                new List<vw_Client_info>().Where(c=> c.Recstatus != 1);
      

      或者

      var searchResult = 
               new List<vw_Client_info>().Where(c=> c.Recstatus != 1);
      

      同上(编译器为你派生类型)

      或者

      List<vw_Client_info> searchResult = 
               new List<vw_Client_info>().Where(c=> c.Recstatus != 1).ToList();
      

      【讨论】:

        猜你喜欢
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多