Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ to objects stop processing Any() when condition is true?

Consider the following:

bool invalidChildren = this.Children.Any(c => !c.IsValid());

This class has a collection of child objects that have an IsValid() method. Suppose that the IsValid() method is a processor intensive task. After encountering the first child object where IsValid() is false, theoretically processing can stop because the result can never become true. Does LINQ to objects actually stop evaluating after the first IsValid() = false (like a logical AND) or does it continue evaluating all child objects?

Obviously I could just put this in a foreach loop and break on the first invalid result, but I was just wondering if LINQ to objects is smart enough to do this as well.

EDIT: Thanks for the answers, for some reason I didn't think to look it up on MSDN myself.

like image 421
Carvellis Avatar asked Mar 21 '11 17:03

Carvellis


1 Answers

Yes it does. As soon as it finds a match, the criteria is satified. All is similar in that it checks all items but if one doesn't match it ends immeditately as well.

Exists works in the same manner too.

Any

The enumeration of source is stopped as soon as the result can be determined.

Exists

The elements of the current List are individually passed to the Predicate delegate, and processing is stopped when a match is found.

All

The enumeration of source is stopped as soon as the result can be determined.

etc...

like image 111
Kelsey Avatar answered Oct 21 '22 06:10

Kelsey