开发者

Question of LINQ optimisation

开发者 https://www.devze.com 2023-03-10 05:22 出处:网络
If I have the following code, is the compiler instanti开发者_运维知识库ating each result or is it wise enough to just count how many corresponding records are in the table? If not, it may force me to

If I have the following code, is the compiler instanti开发者_运维知识库ating each result or is it wise enough to just count how many corresponding records are in the table? If not, it may force me to use a different strategy on larger queries.

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

Thank you!


It depends on the type of context.

If this is an Entity Framework or Linq to SQL query, and context is IQueryable<T>, then the query gets turned into a SQL query on the server which just returns the count as a single integer.

If this is an in-memory collection (ie: IEnumerable<T>), each item is iterated in sequence (Linq to Objects) and counted.

I suspect the former is true, since you mentioned "table" and you're not using the LINQ to Dataset extension methods. In that case, you will stay very efficient.


This will execute (more or less):

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

Linq will add no real overhead to the query and the count will be processed server-side.


This will execute a SQL query with the three WHERE conditions you listed and return the count of the matching rows, it will only materialize the actual count, not each row - if that was your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消