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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With