LINQ optimization issue

If I have the following code, does the compiler instantiate each result, or is it enough to count how many matching records are in the table? If not, this may force me to use a different strategy for larger requests.

from c in context.RendezVous where c.RepID == repID && c.DateHeureRV != null && c.DateHeureRV.Value.Date == date.Date select c).Count(); 

Thanks!

+4
source share
3 answers

It depends on the type of context .

If it is an Entity Framework or Linq to SQL query, and context is IQueryable<T> , then the query turns into an SQL query on the server, which returns only a number as a single whole.

If it is a collection in memory (i.e. IEnumerable<T> ), each element is repeated in sequence (Linq to Objects) and counted.

I suspect the first is true, since you mentioned the β€œtable” and you are not using LINQ to Dataset extension methods. In this case, you will remain very effective.

+4
source

This will execute (more or less):

 select count(*) from rendezvous where repid='...' and dateheurerv is not null and dateheurerv='...' 

Linq will not add any real request overhead, and the counter will be processed on the server side.

+2
source

This will execute the SQL query with the three WHERE conditions you specify and return the score of the matching rows, it will materialize the actual score, and not each row - if that is your question.

+1
source

All Articles