tags:

views:

50

answers:

2

Something very strange is happening in my program:

I make this query agt.DefaultNr == 1 on a collection and get 3 items as Result:

IEnumerable<Agent> favAgents =
            from agt in builtAgents where agt.DefaultNr == 1 select agt;

For every item I set the DefaultNr = 0

foreach (Agent noFavAgt in favAgents)
{
    noFavAgt.DefaultNr = 0;
}

I do another query but for some reason my favAgents collection is empty now!

IEnumerable<Agent> smallAgents = (from agt in favAgents
    where agt.tempResultCount < 30
    orderby agt.tempResultCount descending
    select agt);

What is going on here?

Is this a LINQ lazy loading problem?

Looks like there will be some kind of re-query after I set all items = 0 because I my collection is empty!

+4  A: 

Yes, your favAgents collection will be empty now - you've "turned off" the bit in each element of it that made it match the query! If you iterate over favAgents twice, it will execute the query twice. favAgents represents the query itself, not the results.

If you want to preserve one particular set of results, use ToList or something similar:

favAgents = favAgents.ToList();

That will materialize the query - perform it once and then remember the results in a list, basically. ToArray would have the same effect, but store the results in an array instead.

Jon Skeet
+8  A: 

This is not lazy loading, it's deferred execution. When you define your initial enumerable, you're defining a query, not a collection. You're correct that it's performing a requery; every time you iterate over favAgents, it will execute the query that you defined. If you want to create a list based off of that query that doesn't change, add ToList().

var favAgents = 
    (from agt in builtAgents where agt.DefaultNr == 1 select agt).ToList();

Doing this will create a list in memory and cache the results of the query at that point in time.

Adam Robinson
Thanks. I learned something new today.
Holli