tags:

views:

48

answers:

1

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.

+4  A: 

This line is the culprit:

return oCurrentLabourTrans as Collection<JCTransLabour>;

oCurrentLabourTrans is not a Collection<JCTransLabour>, and thus the as operation returns null, as expected. If you were to do this instead:

return (Collection<JBTransLabour) oCurrentLabourTrans;

the cast would fail and an InvalidCastException would be thrown. LINQ operators produce objects which implement IEnumerable<> directly; they do not automatically create collection and list objects.

If you have to return a Collection<>, you can do this instead:

return new Collection<JCTransLabour>(oCurrentLabourTrans.ToList());
Bryan Watts
On a side note, if you do this a lot you can create a custom extension that converts to a Collection<>
Bryce Fischer