0

I am having below like code in asp.net mvc controller...

IEnumerable<object> object = null;
IEnumerable<object1> object1 = null;

object = object1.where(s=>s.IsActive);

If(object.Any())
{
    ...
}

or

if(object.Count > 0)
{
    ...
}

My question is, if any data exists in "object" will the object.Any() and object.Count > 0 both will return same result (true or false) or both are different?

Please, can anyone help me on this?

SDK
  • 1,532
  • 1
  • 15
  • 31

3 Answers3

8

Any will be faster because (in your case IEnumerable <object>) it returns true as soon as first element matching your condition is found.

Whereas Count has to go till the end of the collection (read iterate collection) to get its result.

Food4Thought:
1. Yours will throw exception because collection is null.
2. object1.Where (s => s.IsActive); will show compile time exception on s.IsActive because collection is of object type and IsActive is not a property in object class. Change it to IEnumerable<My_Class_Which_Have_Is_Active_Property>.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

Count() needs to iterate through the whole collection. Any() returns when it encounters the first item.

Any() is faster.

Skrealin
  • 1,114
  • 6
  • 16
  • 32
1

I would recommend Any().

It's neater and easier to read and it doesn't need to count all elements to yield return a value.

A lot depends on the underlying type. In your case IENumerable (IE not IQueryable with an ORM underneath) the difference is negligible - depending on the size of the collection. With an ORM like EF Any can prove to be considerably more peformant.

reckface
  • 5,678
  • 4
  • 36
  • 62
  • I agree that the semantic of Any suggests it would be more performance, but this entirely depends on the implementation of the underlying enumerator. In some cases this might not be any faster, but as you say, its very likely to be. – PhillipH Jul 15 '14 at 10:20