tags:

views:

62

answers:

3

This question led me to wonder the following:

What are the 'Gotchas' associated with tacking on a ToList() to a Linq-to-Sql query?

I'm equally interested in best practices and anecdotes.

A: 

Disregarding transactions:

using (PlayerDataContext context = new PlayerDataContext())
{
    var players = context.Players.ToList();
    MethodThatUnexpectedlyTakes25SecondsToComplete();
    Console.WriteLine(players.Count()); // Outputs a stale count
}
Jim G.
I don't really see how that is a "gotcha". ToList() clearly copies the entities from Players into a List<T>. That's what ToList does on any IEnumerable.
Rex M
I don't agree that this is stale... this is an absolutely 100% up-to-date of the number of items in the list, which is what you asked it to do... this is just disconnected data.
Marc Gravell
Also, I'd argue it DOES output a stale count (not could do so). The fact that the stale count might coincide with the actual count is beside the point.
Matthew Scharley
Alright, I agree with Marc, even if he did beat me by 17 seconds. The count isn't stale, it's a count of the number of items in the list. It's the list that is always stale. Semantics, bleh.
Matthew Scharley
+1  A: 

The big one is the loss of deferred execution. A linq query normally doesn't actually do anything until you iterator over the results. Calling .ToList() iterates over the results, and so will run the query right away.

Joel Coehoorn
A: 

Compromising linq-to-sql's ability to optimize:

using (PlayerDataContext context = new PlayerDataContext())
{
    // suboptimal
    var players = context.Players.ToList();
    Console.WriteLine(players.Count());

    // optimal
    var playerCount = context.Players.Count();
    Console.WriteLine(playerCount);
}
Jim G.
This is super obvious...it isn't a gotchya...
jjnguy
jjnguy -You'd be surprised. I see this a lot in our Production code.
Jim G.