What's the best way to iterate a linq resultset?

Posts   
 
    
NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 02-Apr-2009 00:56:10   

LLBLGen Pro v2.6 Adapter

So I've filled up an entity collection: EntityCollection<QueueEntity>

I want to find all the QueueEntities inside that collection that have an NcsPriority of < 2.0, so I did this:

var lifeAndSafetyQueue = from cq in queue.CallQueue
                                            where Convert.ToDouble(cq.CallLog.NcsPriority) < 2.0
                                            select cq;

...just a little later, I attempt to "foreach" through that resultset. If the resultset is empty because there are no records where NcsPriority is less than 2.0, I get a

"Object reference not set to an instance of an object."

...error. The error is generated at the point when the lifeAndSafetyQueue is referenced in the foreach loop. I've tried wrapping the foreach loop in an "if" test:

if (lifeAndSafetyQueue.Count() > 0) {

...but then I get the error at that point. What's a programmer to do?

Seth avatar
Seth
User
Posts: 204
Joined: 25-Mar-2006
# Posted on: 02-Apr-2009 01:08:08   

So I think a good foundation on what exactly a queryable is might help. I like to think of it as a unit of deferred execution. The best way to "materialize" the queryable is to cast it as an ILLBLGenProQuery and call the Execute method to actually create the EntityCollection. Then you can work with it as you would any other collection. If I didnt explain properly let me know!

NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 02-Apr-2009 01:39:34   

I have a feeling we're mixing technologies here. When you say "a queryable", you're talking about Linq terms, right? So, help me increase my Linq knowledge. Since my query is deferred execution, why does attempting to get a count of zero return an "Object not found" reference? Why doesn't it return zero?

Now, I do certainly understand what you're saying about using an LLBLGenProQuery to do the same thing, but I guess I'm after the Linq approach for Linq's sake.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 02-Apr-2009 06:15:14   

Yes, It's not clear if you want to take advantage of LINQ2LLBL or LINQ2Objetcts, which are different things. Also, the exception stack trace would help here to figure this out. What is queue.CallQueue?

David Elizondo | LLBLGen Support Team
NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 02-Apr-2009 23:54:59   

Yeah, well, it turns out it was just my misunderstanding of how linq works. I've figured out a way to do it that is better. Thanks for getting me going in the right direction though.

Seth avatar
Seth
User
Posts: 204
Joined: 25-Mar-2006
# Posted on: 03-Apr-2009 01:49:41   

I just barely started understanding it myself. Here is something I put together that has helped me (at least) and hopefully some of the people that listened to my lecture.