I have list of objects. I want to find the count of items in the list that satisfy a specific conditions. I have two options LINQ or foreach loop. I can write a LINQ query to find the count or can iterate the items using foreach and set a counter on a condtion. I want to know the optimize way of doing it whether I use foreach or LINQ to find count. thanks in advance.
-
Show us your code please. – Ufuk Hacıoğulları Oct 10 '14 at 14:13
-
3Answer is: it depends – DavidG Oct 10 '14 at 14:14
-
I asked something similar time ago. http://stackoverflow.com/questions/23126954/fast-way-to-iterate-and-set-counters-based-on-properties – blfuentes Oct 10 '14 at 14:15
-
1Build yourself a test scenario and try both solutions, you should be able to tell the performance difference for your example, but be sure you do multiple tests and a big enough data mass to get useful test results. – Paul Weiland Oct 10 '14 at 14:16
-
1Not quite sure I understand the upvotes to this question, as this is [easily researched](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23%20which%20is%20faster%20linq%20or%20foreach) – crthompson Oct 10 '14 at 14:24
-
@paqogomez : it's not because of entity-framework tag – Pleun Oct 10 '14 at 21:39
-
@Pleun, the first link in my google link goes to [Marc Gravell's excellent answer](http://stackoverflow.com/a/3156097/2589202) on this topic. I found it in 5 seconds. I call that easy. – crthompson Oct 11 '14 at 00:46
2 Answers
Linq's Count()
method is implemented using a loop, so it doesn't really matter which you use. An explicit loop will probably be slightly faster, but I don't think the difference will be large enough to be noticed. I would use Count(predicate)
because it's more readable.
EDIT: I had not noticed the Entity Framework tag in your question, so I was assuming it was Linq to Objects. If you're querying against a database, using Count(predicate)
will definitely be faster; using a loop would mean that you fetch each record from the DB to check it in your code, while the call to Count
will be converted to a SQL query to be executed on the DB.

- 286,951
- 70
- 623
- 758
-
He has EF as a tag so it's possible that `Count` will be passed to DB to work out which will be faster than iterating. – DavidG Oct 10 '14 at 14:17
-
Well, since you mention entity framework: probably Linq because it will execute the count in the database where possible. Assuming again that your filter criteria can be translated into SQL
If you were to retrieve all the entities first from the DB and after that apply the filter, this could cause a lot of overhead.

- 8,856
- 2
- 30
- 50