Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Linq retrieve all records first if I do a Count?

Tags:

c#

linq-to-sql

Assume I have a table called Population that stores some demographic data. In T-SQL, to get the count of people over 50, I might do something like this:

SELECT COUNT(*) FROM POPULATION
WHERE AGE > 50

I thought the following linq statement would work, but it just returns zero and I don't understand why.

var count = _context.Population.Count(x => x.Age > 50);

In order for me to actually get the count, I have to do either of the following:

var count = _context.Populaton.Where(x => x.Age > 50).Count();

var count = _context.Population.Select(x => x.Age > 50).Count();

Why are the above scenarios the case?

like image 785
Xaisoft Avatar asked Jan 18 '11 02:01

Xaisoft


2 Answers

Linq does not retrieve all the records first. It defers the execution of the query until last possible moment. This allows the query to be optimized.

http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx

I have found that order is important sometimes. Hope this helps.

Bob

like image 97
rcravens Avatar answered Nov 17 '22 10:11

rcravens


In all cases Count() will NOT do the computation in memory based on the records returned from the database, but it will actually change the generated SQL to include the COUNT statement. A simplistic version of your generated TSQL query would be something like:

SELECT 
    COUNT(1)
    FROM [dbo].[Population] AS [Extent1]
    WHERE [Extent1].[Age] > 50

When you call Count() the query is executed immediately. All your queries seem to be correct, so check your database, provider and context to make sure the query is executing properly.

like image 1
b-s-d Avatar answered Nov 17 '22 09:11

b-s-d