Cornel Marian
Cornel Marian

Reputation: 2503

Best way to use Count() in LINQ?

I have this line of code

var count = materials.Where(i => i.MaterialType1 == MaterialType.Major).Count(); 

which Resharper prompts me to change to

var count = materials.Count(i => i.MateriakType1 == MaterialType.Major); 

Why? Anyone enlighten me on what the benefits of changing are?

Upvotes: 5

Views: 804

Answers (2)

KrishnaDhungana
KrishnaDhungana

Reputation: 2684

I think it depends on how you want to use it. Lets say you have a query:

var query=materials.Where(i => i.MaterialType1 == MaterialType.Major);
var query2=query.  ... sub query
var result=query.   ... some operation
var result=query.Count() ;

If you write with deferred execution in mind then I would prefer writing queries first and use it accordingly (rather than using greedy operators like Count()) but as I said depends upon the scenario.

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

I would not say the second one if always worse. It depends on context.

For LINQ to Objects it's better to use the second one, because it suppose to be faster. I didn't test that, so that's really only my guess.

However, be careful with changes like this one, because they are not always equivalent. E.g. if you used LINQ to Entities the second one would not work at all! That's because Count overload with predicate is not supported by LINQ to Entities.

Upvotes: 5

Related Questions