Linq - why Count when there's Any?

in #c3 years ago (edited)

In not so few instances I've stumbled upon C# code along the lines of:


bool areThereAny = someEnumerable.Where(elem => someCondition(elem)).Count > 0;

The intention here is to determine whether that IEnumerable contains any elements satisfying someCondition.

If that is really the case then why do we Count the elements? We don't really need to Count them, we only want to know if there are any.

And if we really need a count AND if areThereAny, then areThereAny has no use to us, we don't really need it (except when required by some legacy code further down). Or we can just set


int howMany = someEnumerable.Where(elem => someContition(elem)).Count;
bool areThereAny = howMany > 0;
//... code using howMany and areThereAny ...

Now, back to the previous case: ok, I don't need to count stuff, but how do I know whether areThereAny? Well, just use linq's Any! And the above snippet becomes:

bool areThereAny = someEnumerable.Any(elem => someCondition(elem));
        

But Why?!

Well, two reasons come to mind right now:
  • Just a bit more performance

    Because Where...Count goes over all the elements in the IEnumerable, whereas Any stops at the first element encountered satisfying the condition.

  • It shows that the developer knows what they actually want

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.030
BTC 56587.45
ETH 2991.05
USDT 1.00
SBD 2.15