使用 linq 查询集合时,它总是返回 null
前几天我发布了部分代码,但这样做引起了更多混乱。这是我的代码。
if ( HttpContext.Current.Session != null )
{
if ( HttpContext.Current.Session[ "CurrentLabourTransactions" ] != null )
{
Collection<JCTransLabour> oJCTransLabours = null;
oJCTransLabours = (Collection<JCTransLabour>)HttpContext.Current.Session["CurrentLabourTransactions"];
if (Settings.ShowTodaysTransactionInApproval)
if (oJCTransLabours != null) return oJCTransLabours;
if (oJCTransLabours != null)
{
//oJCtransLabour contains alot of record
var oCurrentLabourTrans = (from clt in oJCTransLabours
where clt.TransactionDate.Date != DateTime.UtcNow
select clt);
//oCurrentLabourTrans is null.
return oCurrentLabourTrans as Collection<JCTransLabour>;
}
}
}
return null;
当进入最后的 if 语句时,有很多具有不同日期的交易。看起来虽然它总是返回空记录。
预先感谢您的任何帮助。
I posted up part of some code the other day but in doing so caused more confusion. This is my code.
if ( HttpContext.Current.Session != null )
{
if ( HttpContext.Current.Session[ "CurrentLabourTransactions" ] != null )
{
Collection<JCTransLabour> oJCTransLabours = null;
oJCTransLabours = (Collection<JCTransLabour>)HttpContext.Current.Session["CurrentLabourTransactions"];
if (Settings.ShowTodaysTransactionInApproval)
if (oJCTransLabours != null) return oJCTransLabours;
if (oJCTransLabours != null)
{
//oJCtransLabour contains alot of record
var oCurrentLabourTrans = (from clt in oJCTransLabours
where clt.TransactionDate.Date != DateTime.UtcNow
select clt);
//oCurrentLabourTrans is null.
return oCurrentLabourTrans as Collection<JCTransLabour>;
}
}
}
return null;
When going into the final if statement there are a lot of transactions with different dates. It seems to although it always returns null records.
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行是罪魁祸首:
oCurrentLabourTrans
不是Collection
,因此as
操作返回 null ,正如预期的那样。如果您这样做:转换将会失败,并且会抛出
InvalidCastException
。 LINQ 运算符生成直接实现IEnumerable
的对象;它们不会自动创建集合和列表对象。如果您必须返回
Collection<>
,您可以这样做:This line is the culprit:
oCurrentLabourTrans
is not aCollection<JCTransLabour>
, and thus theas
operation returns null, as expected. If you were to do this instead:the cast would fail and an
InvalidCastException
would be thrown. LINQ operators produce objects which implementIEnumerable<>
directly; they do not automatically create collection and list objects.If you have to return a
Collection<>
, you can do this instead: