Thursday, May 7, 2009

LINQ: Any() or Count()

Update 1 july: Also information about the ToDictionary method

When you have a collection and you want to check if there are items in the collection you can do this

Codefragment 1:

if (lCollection.Count() > 0) {
// do something
}


Codefragment 2:

if (lCollection.Any()) {
// do something
}


When the collection is also an ICollection the Count property is returned otherwise the collection is enumerated an counted for each element. The last one is an expensive operation.

The Any() method begins to iterate over the collection and stops when the condition is true. If you use the variant without the condition, the method iterates over the first element and stops. So code fragment 2 is a better solution qua performance.

No comments:

Post a Comment