7
How to count records that a query would return in Linq (Entity Framework) in C#? The equivalent in SQL is to do a SELECT COUNT(*)
.
Note that I want to receive the count of records straight away, just as a SELECT COUNT(*) would, and not receive the results and do a count afterwards. Then a .Select().Count()
or a .Where().Count()
doesn’t solve my situation. Neither does that:
var result = from tbl in tabela
select tabela;
int contagem = result.Count();
How would it be to perform other operations in a single query, for example: Min, Max, or arithmetic operations between two queries (ex: SELECT(...)/SELECT COUNT(*)
)?
My question is how the function works
.Count()
(and similar class methodsEnumerable
). Does it not operate on variables that already contain data collections (Lists)? Because by the size of the table I’m looking at, I can’t save the results in a variable and then count the number of records for that variable.– diogoan
When using Linq-to-entities, the methods would not be about the
IEnumerable
but rather about aIQueryable
... that’s why select it withCOUNT(*)
is only executed when the methodCount()
is called.– Miguel Angelo
Remembering that a
IQueryable
is aIEnumerable
. The reason why theCount
is executed immediately because it has no deferred execution. You receive as direct return the resultint
, instead of aIQueryable
– Conrad Clark
Got it! Thank you both very much!
– diogoan
What I meant was that the method
Count()
being called is a specificIQueryable
. It is an Extension-method in the classSystem.Linq.Queryable
. If you try to use the methodSystem.Linq.Enumerable.Count(enumerable)
and pass the object, then the query will be executed bringing all records, and then the count.– Miguel Angelo
I mean, don’t do that:
(result as IEnumerable<T>).Count()
– Miguel Angelo