【问题标题】:When querying a collection using linq it always returns a null使用 linq 查询集合时,它总是返回 null
【发布时间】:2010-09-30 14:22:43
【问题描述】:

当使用 linq 查询集合时,它总是返回 null

Collection<JCTransLabour> oJCTransLabours = null;

oJCTransLabour = HttpContext.Current.Session["CurrentLabourTransactions"] as 
                                  Collection<JCTransLabour>;

// at this point the collection oJCTransLabours contains 3500 records

var oCurrentLabourTrans = from clt in oJCTransLabours
                          where clt.TransactionDate.Date != DateTime.Now.Date
                          select clt;

// at this point the collection oJCTransLabour = null
// I have tried to search on different fields 

return oCurrentLabourTrans;

一定是我做错了什么。任何帮助将不胜感激。

【问题讨论】:

  • 第一步之后,是变量oJCTransLabour真的不为null,还是HttpContext.Current.Session["CurrentLabourTransactions"]不为null,因为c#中的'as Collection'运算符返回null如果类型不匹配,则与 (Collection) 变量相反,它会给出异常。
  • 附带说明,请注意DateTime.Now。查看DateTime.UtcNow

标签: c# linq collections


【解决方案1】:

您的问题中至少有一个错字。
你说之后

oJCTransLabour = HttpContext.Current.Session["CurrentLabourTransactions"] as Collection<JCTransLabour>;

oJCTransLabour 不为空,对吧?如果 session 包含它,这是有道理的。

然后定义oCurrentLabourTrans 并将LINQ 查询分配给它。然后你说

// at this point the collection oJCTransLabour = null

等等,它怎么可能是空的?你甚至没有修改它(它是 oCurrentLabourTrans 修改的),你只是说 oJCTransLabour 不为空!

更新:我刚刚注意到名称中也有类型:你称之为oJCTransLabours,然后你称之为oJCTransLabour。请发布准确的代码,这样我们就不会对您可能输入错误的确切内容做出假设。

当然,LINQ 表达式不能为空。 我认为oJCTransLabours 很可能为空,尽管您另有说明。

您这么认为的原因可能是因为您确定HttpContext.Current.Session["CurrentLabourTransactions"] 不为空。这是真的,但您使用as 运算符将值转换为Collection&lt;JCTransLabour&gt;。与强制转换运算符相反,as 在类型不匹配时不会抛出异常,它只会返回 null

你可以试试

oJCTransLabour = (Collection<JCTransLabour>)HttpContext.Current.Session["CurrentLabourTransactions"];

并查看是否出现任何错误。

【讨论】:

    【解决方案2】:

    我认为您只是混淆了变量名称:

    // You were missing an 's' before
    oJCTransLabours = HttpContext.Current.Session["CurrentLabourTransactions"] 
                                        as Collection<JCTransLabour>;
    

    【讨论】:

      【解决方案3】:

      这看起来不像是 linq 问题,而是会话中的值为 null 或不是 Collection&lt;JCTransLabour&gt;

      您可以通过将查找更改为:

      oJCTransLabour = (HttpContext.Current.Session["CurrentLabourTransactions"] as Collection<JCTransLabour>) ?? new Collection<JCTransLabour>();
      

      如果应该始终存在会话值,那么如果在执行查询之前未找到该值,则可以引发异常。

      【讨论】:

        【解决方案4】:

        试试这个:

        var oCurrentLabourTrans = (from clt in oJCTransLabours where clt.TransactionDate.Date != DateTime.Now.Date select clt).ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-15
          • 2018-09-18
          • 2019-11-26
          • 2018-03-05
          • 1970-01-01
          • 2020-06-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多