C# 使用linq查询集合时,它总是返回null
前几天我发布了一些代码的一部分,但这样做造成了更多的混乱。这是我的密码C# 使用linq查询集合时,它总是返回null,c#,linq,object,C#,Linq,Object,前几天我发布了一些代码的一部分,但这样做造成了更多的混乱。这是我的密码 if ( HttpContext.Current.Session != null ) { if ( HttpContext.Current.Session[ "CurrentLabourTransactions" ] != null ) { Collection<JCTransLabour> oJCTransL
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(HttpContext.Current.Session!=null)
{
if(HttpContext.Current.Session[“CurrentLabourTransactions”]!=null)
{
集合oJCTransLabours=null;
oJCTransLabours=(集合)HttpContext.Current.Session[“CurrentLabourTransactions”];
如果(设置。ShowTodayStranSactionApproval)
如果(oJCTransLabours!=null)返回oJCTransLabours;
如果(oJCTransLabours!=null)
{
//oJCtransLabour包含大量记录
var oCurrentLabourTrans=(来自OjCtrTransLabours中的clt
其中clt.TransactionDate.Date!=DateTime.UtcNow
选择clt);
//oCurrentLabourTrans为空。
返回oCurrentLabourTrans作为集合;
}
}
}
返回null;
当进入最终的if语句时,有许多日期不同的事务。虽然它总是返回空记录,但它似乎是正确的
提前感谢您的帮助。这句话是罪魁祸首:
return oCurrentLabourTrans as Collection<JCTransLabour>;
强制转换将失败,并将抛出一个InvalidCastException
。LINQ操作符生成直接实现IEnumerable
的对象;它们不会自动创建集合和列表对象
如果必须返回一个集合
,则可以执行以下操作:
return (Collection<JBTransLabour) oCurrentLabourTrans;
return new Collection<JCTransLabour>(oCurrentLabourTrans.ToList());
返回新集合(oCurrentLabourTrans.ToList());
这一行是罪魁祸首:
return oCurrentLabourTrans as Collection<JCTransLabour>;
强制转换将失败,并将抛出一个InvalidCastException
。LINQ操作符生成直接实现IEnumerable
的对象;它们不会自动创建集合和列表对象
如果必须返回一个集合
,则可以执行以下操作:
return (Collection<JBTransLabour) oCurrentLabourTrans;
return new Collection<JCTransLabour>(oCurrentLabourTrans.ToList());
返回新集合(oCurrentLabourTrans.ToList());
您的意思是它总是返回null,还是总是返回一个空行集合?是“oCurrentLabourTrans”null还是“oCurrentLabourTrans as collection”null?可能是的重复项?您是否已使用调试器对此进行了测试?集合对象中是否填充了数据?如果不了解更多关于数据源的信息以及您已经采取了哪些故障排除步骤,就很难说问题出在哪里。那么哪一行返回空值呢?注释oJCtransLabour后的那一行是否包含大量记录
?您的意思是它总是返回null,还是它总是返回一组空行?是“oCurrentLabourTrans”null还是“oCurrentLabourTrans as collection”null?是否可能重复?是否已使用调试器对此进行了测试?集合对象中是否填充了数据?如果不了解更多关于数据源的信息以及您已经采取了哪些故障排除步骤,就很难说问题出在哪里。那么哪一行返回空值呢?注释oJCtransLabour后的那一行是否包含大量记录
?在旁注上,如果您经常这样做,您可以创建一个转换为集合的自定义扩展名在旁注上,如果您经常这样做,您可以创建一个转换为集合的自定义扩展名