Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the difference between .Select, .Any, and .Count when using LINQ

Tags:

linq

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!

like image 512
Alex Avatar asked May 18 '11 00:05

Alex


1 Answers

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.

like image 84
Kirk Broadhurst Avatar answered Jan 01 '23 07:01

Kirk Broadhurst