I was wondering if I do something like:
var results = source.Where(c => c.Name == "Whatever");
is there any way to check if the query returned anything before calling Count() or ToList() ? I know Where() executes lazily.
The data set returned might be huge and calling the above methods is quite time consuming.
results is never NULL either…
Thank you.
Since you just want to know if it’s worthwhile to get the full result set this is never worth doing.
There are only two situations here:
There are no results for your query. In this case, the query to check how many results there are will take exactly as long to execute, and return exactly as much information, as the real query. You gain nothing (but also lose nothing) in this case.
There is at least one result to your query. In this case you need to go back and execute the real query. The net result is that you spent just as much time as you would have by not checking first, but you also have the added cost of checking if there are results. That check means a round trip to the database, which is a non-trivial amount of time.
If you want to know if a query will contain any items it’s possible. (Just use the
Anyextension method.) However, it’s only beneficial if you don’t need to know what the actual items are regardless of what the result ofAnyis.It’s also worth noting, as lazyberezovsky did in his answer, that you also need to consider the race condition where the results of the query change after you call
Any.