简体   繁体   中英

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?

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. Eg 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM