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

前端 未结 5 1009
醉话见心
醉话见心 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条回答
  • 2021-01-04 03:37

    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...

    0 讨论(0)
  • 2021-01-04 03:40

    Yes it will stop after it encounters the first item for which the condition matches, in your case the first item for which c.IsValid() returns false.

    From MSDN:

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

    0 讨论(0)
  • 2021-01-04 03:48

    as per MSDN,

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

    0 讨论(0)
  • 2021-01-04 03:55

    Yes, it stops as soon as the results can be evaluated. Here's a quick proof:

    class Program
        {
            static void Main(string[] args)
            {
                bool allvalid = TestClasses().Any(t => !t.IsValid());
                Console.ReadLine();
            }
    
            public static IEnumerable<TestClass> TestClasses()
            {
                yield return new TestClass() { IsValid = () => { Console.Write(string.Format("TRUE{0}",Environment.NewLine)); return true; } };
                yield return new TestClass() { IsValid = () => { Console.Write(string.Format("FALSE{0}", Environment.NewLine)); return false; } };
                yield return new TestClass() { IsValid = () => { Console.Write(string.Format("TRUE{0}", Environment.NewLine)); return true; } };
                yield return new TestClass() { IsValid = () => { Console.Write(string.Format("TRUE{0}", Environment.NewLine)); return true; } };
            }
        }
    
        public class TestClass
        {
            public Func<bool> IsValid {get;set;}
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题