68

When I want to do something with a list I first check it if is not null or contains no elements (not to blow a foreach) and I usually use list.Any() but what is the best option - to use list.Count > 0 , or to use list.Any()?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Dominating
  • 2,890
  • 7
  • 25
  • 39
  • 1
    per style-guide: a list (collection, whatever) should never be null - rather it should be empty ... –  Apr 21 '11 at 08:58
  • Better to use Any() on Enumerables and Count on Collections. If someone feels writing '(somecollection.Count > 0)' will confuse or cause readability issues, better write it as an extension method name it Any(). Then everyone satisfied. Performance-wise as well as Readability-wise. So that all your code will have consistency and individual developer in your project need not worry about choosing Count vs Any. – Mahesh Bongani Jun 06 '19 at 18:44

5 Answers5

109
  • Use Count if you're using a List, since it knows its size.
  • Use Length for an Array
  • If you just have an IEnumerable I would use .Any() over .Count() as it will be faster since it stops after checking one item.

Also check out this question: Which method performs better: .Any() vs .Count() > 0?

ruffin
  • 16,507
  • 9
  • 88
  • 138
Ray
  • 45,695
  • 27
  • 126
  • 169
  • 2
    Don't! - If you can, __always__ use `Any` as it will translate to `Count` or `Length` wherever possible anyway and give a clear and uniform intention. – TaW Apr 11 '19 at 07:10
  • 9
    @TaW _always use Any as it will translate to Count or Length wherever possible anyway_ Can you back this up with some source code, because I don't believe you. Sorry. – Silvermind Aug 21 '19 at 12:23
  • I had reported the things I had found in various comments and posts but looking at the [sources](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,6a1af7c3d17845e3) I have my doubts. I would still recommend Any() unless it would involve at trip to a database; but for other cases I doubt there would be any measurable performance hit (not sure how those casts factor in) and the clearer code remains a good reason. – TaW Aug 21 '19 at 13:11
  • 1
    @Silvermind Within the current dotnet runtime this will be used: https://github.com/dotnet/runtime/blob/v5.0.5/src/libraries/System.Linq/src/System/Linq/AnyAll.cs#L11-L45 As for .NET framework there is no such check and thus `.Count` is prefered over `.Any()`. Interesting – Baklap4 May 07 '21 at 12:21
  • 1
    Hey @Baklap4. I had the same argument here and if you read it you'll see I can make it break, but I have seen the source. ;) https://stackoverflow.com/a/66824318/858757 – Silvermind May 07 '21 at 13:39
  • Maybe have a look at the [benchmarks](https://www.tabsoverspaces.com/233649-comparing-speed-of-count-0-and-any). – Flimtix Apr 20 '22 at 08:04
4

I use list.Count > 0 just because it doesn't depend on the LINQ methods and so works on C# 2.0.

I personally avoid LINQ like the plague (because of its slow speed), and there's no reason to use extension methods here at all anyway.

However, a better solution would probably be to make your own version of Any that would take in a null reference, and return true if it's a collection with elements. That would save you the null check.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • 10
    LINQ may be slower than something like a for-loop; but its not that slow that it should be avoided. I believe its worth the small performance hit since it makes the code more maintainable. – Phil Jul 29 '16 at 16:06
4

.Any() is generally better to use than .Count() > 0. The reason for this is that if the items you are iterating over is not an ICollection then it will have to iterate the whole list to get the count.

But if the items is an ICollection (which a List<T> is) then it is just as fast or in some cases faster to use Count() (Any() iterates once regardless of underlying type in MS .Net but Mono tries to optimize this to Count > 0 when the underlying items is an ICollection)

A great tool is Reflector, the .Net source code and the Mono source code which allows you to see how things are implemented.

Rick Love
  • 12,519
  • 4
  • 28
  • 27
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • 5
    btw ... .NET Reflector is non-free since version 7. an alternative: ILSpy (http://wiki.sharpdevelop.net/ilspy.ashx) –  Apr 21 '11 at 09:02
  • @Andreas Niedermair : Why you said IEnumerable is the evil interface / class ??? – Florian Mar 21 '12 at 13:15
  • @Florian pfuh ... 1 year later ... no plan ... sry pal - i should rather delete the cmt :) –  Mar 21 '12 at 13:35
  • 1
    It doesn't appear that Mono optimizes the Any() to Count > 0 from this source code (it seems identical to the .net implementation): https://github.com/mono/mono/blob/master/mcs/class/referencesource/System.Core/System/Linq/Enumerable.cs – Rick Love Oct 22 '18 at 14:23
2

If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().

ashlar64
  • 1,054
  • 1
  • 9
  • 24
1

Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

Janmejay Kumar
  • 309
  • 2
  • 7