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

前端 未结 5 1081
醉话见心
醉话见心 2021-01-04 03:21

Consider the following:

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

This class has a collection of child objects that h

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 03:56

    Here's a quick and dirty empirical test to see for yourself:

    class Kebab
    {
        public static int NumberOfCallsToIsValid = 0;
    
        public bool IsValid()
        {
            NumberOfCallsToIsValid++;
            return false;
        }
    }
    
    ...
    
    var kebabs = new Kebab[] { new Kebab(), new Kebab() };
    kebabs.Any(kebab => !kebab.IsValid());
    
    Debug.Assert(Kebab.NumberOfCallsToIsValid == 1);
    

    The result is that yes, the Any LINQ operator stops as soon as a collection item matches the predicate.

提交回复
热议问题