What are the difference between .Select, .Any, and .Count when using LINQ Do you get a performance hit when using .Count just like in SQL select count(*)? Does .Any perform faster ?
Thanks!
Count
needs to iterate the entire collection, because it (obviously) needs to count the number of instances.
Any
finds the first occurrence & returns true or false. If there aren't any, then it needs to iterate the whole collection to try to find, but if the first instance matches then it only needs to check the first instance.
Select
is completely different. It is used to project a collection into another collection. It does not perform any checking or filtering.
edit: In SQL terms, Any
is like Exists
, while Count
is like Count(*)
.
If I want to know whether there are any people on the street today, it is completely unnecessarily to count all the people and see if the number is >= 1. As soon as I find one person then I'm done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With