Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use Count() in LINQ?

Tags:

c#

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?

like image 433
Cornel Marian Avatar asked Oct 21 '13 05:10

Cornel Marian


1 Answers

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.

like image 70
MarcinJuraszek Avatar answered Oct 11 '22 01:10

MarcinJuraszek