patterncsharpModerate
Is it a good way to get Count on Linq?
Viewed 0 times
linqwaygetgoodcount
Problem
public class BuscaDiretaBusiness
{
PortalIOEntities portalIO = new PortalIOEntities();
public IQueryable CarregaAlias(out int ItemsCount)
{
var query = from a in portalIO.DO_CadernoBuscaDiretaAlias
select new
{
a.CDP_ID,
a.CDA_Alias,
a.DO_CadernoDeParaBuscaDireta.CDP_NomeCaderno
};
ItemsCount = query.Count();
return query;
}
}Will it make two selects on DataBase?
Solution
That method will only hit the DB once, with a query like
You should probably only return the
Also, you probably should not be returning a collection of an anonymous type from a method, because it's hard to use.
SELECT COUNT(*) …. But if you try to enumerate the resulting IQueryable in any way (like calling ToArray() on it or using it in a foreach), it will make another DB query.You should probably only return the
IQueryable. If the consumer needs all the items, it will call ToArray() or similar, which will make one DB query and then look at the Length of the result (which of course won't make another query). If the consumer needs only part of the result (e.g. it will call Take(100)) and it also needs the total count, it will call Count() itself. This will mean there will be two queries, but I think it can't be done differently.Also, you probably should not be returning a collection of an anonymous type from a method, because it's hard to use.
Context
StackExchange Code Review Q#10026, answer score: 11
Revisions (0)
No revisions yet.