开发者

Is this a LINQ lazy loading problem?

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 = (fr开发者_Go百科om 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜