Interview Question: .Any() vs if (.Length > 0) for testing if a collection has elements

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-06-07T12:11:25Z Indexed on 2010/06/07 12:12 UTC
Read the original article Hit count: 232

Filed under:
|
|

In a recent interview I was asked what the difference between .Any() and .Length > 0 was and why I would use either when testing to see if a collection had elements.

This threw me a little as it seems a little obvious but feel I may be missing something.

I suggested that you use .Length when you simply need to know that a collection has elements and .Any() when you wish to filter the results.

Presumably .Any() takes a performance hit too as it has to do a loop / query internally.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ