2010-10-04 71 views
0

我在前一天張貼了一些代碼的一部分,但這樣做導致了更多的混淆。這是我的代碼。當使用linq查詢一個集合時,它總是返回一個空值

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語句時,會有許多具有不同日期的事務。它似乎儘管它總是返回空記錄。

在此先感謝您的幫助。

+0

你的意思是,它總是返回* NULL *,或者它總是返回空行的集合? – 2010-10-04 16:02:19

+1

是'oCurrentLabourTrans'null還是'oCurrentLabourTrans作爲集合'null? – 2010-10-04 16:02:59

+0

[使用linq查詢集合時總是返回null]的可能重複(http://stackoverflow.com/questions/3831490/when-querying-a-collection-using-linq-it-always-returns-a- null) – Guffa 2010-10-04 16:03:51

回答

4

這條線是罪魁禍首:

return oCurrentLabourTrans as Collection<JCTransLabour>; 

oCurrentLabourTrans一個Collection<JCTransLabour>,因此as操作返回null,如所預期。如果你想這樣做,而不是:

return (Collection<JBTransLabour) oCurrentLabourTrans; 

演員將失敗,將會拋出InvalidCastException。 LINQ操作員直接生成實現IEnumerable<>的對象;他們不會自動創建收集和列表對象。

如果你非要返回Collection<>,你可以這樣做,而不是:

return new Collection<JCTransLabour>(oCurrentLabourTrans.ToList()); 
+0

在附註上,如果你這麼做了很多,你可以創建一個自定義的擴展,轉換成一個Collection <> – 2010-10-04 17:06:09

相關問題