Why does IQueryable.All() return true on an empty collection?

后端 未结 11 1643
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:46

So I ran into a situation today where some production code was failing precisely because a method performed exactly as documented in MSDN. Shame on me for not reading the d

相关标签:
11条回答
  • 2020-12-01 05:30

    If the number of the items that return true is the same as the number of all the items, then return true. Simple as that:

    Driveway.Cars(a => a.Red).Count() == Driveway.Cars.Count()
    

    Related explanation: Why does "abcd".StartsWith("") return true?

    0 讨论(0)
  • 2020-12-01 05:33

    You will find this behaviour quite often in other areas of mathematics or computer science.

    The SUM operator in Math will return 0 (the neutral element of +) in cases where the ranges are invalid (the SUM from 0 up to -1). The MULTIPYL operator will return 1 (neutral element for multiplication).

    Now if you have Boolean expressions, it's quite similar: The neutral element for OR is false (a OR false = a) whereas the neutral element for AND is true.

    Now on Linq's ANY and ALL: They are similar to this:

    ANY = a OR b OR c OR d ...
    ALL = a AND b AND c AND d ...
    

    So this behavior is just what "you would expect" if you have a math/cs background.

    0 讨论(0)
  • 2020-12-01 05:35

    "If the collection is empty, a test like this is, at best, undefined. If my driveway is empty, I cannot assert that all cars parked there are red."

    Yes you can.

    To prove me wrong, show me a car on your empty driveway that is not red.

    For anyone familiar with the SQL notion that NULL != NULL, this is unexpected behavior.

    This is a quirk of SQL (and not quite true: NULL = NULL and NULL <> NULL are both undefined, and neither will match any rows.)

    0 讨论(0)
  • 2020-12-01 05:35

    Because any proposition to an empty set would be a vacuous truth.

    0 讨论(0)
  • 2020-12-01 05:35

    It's very similar to the basic concept of the number zero. Even though it represents the existence of absence, it still possesses and represents a value. IQueryable.All() should return true, because it will successfully return all of the members of the collection. It just so happens that if the collection is empty, the function won't return any members, but not because the function couldn't return any members. It was only because there were no members to return. That being said, why should IQueryable.All() have to experience failure due to the lack of support from the collection? It was willing, it was able...it was capable. Sounds to me like the collection couldn't hold up their end of the bargain...

    http://mathforum.org/dr.math/faq/faq.divideby0.html

    0 讨论(0)
  • 2020-12-01 05:39

    Returning true is also logical. You have two statements: "Have a car?" and "Is it red?" If the first statement is false, it doesn't matter what the second statement is, the result is true by modus ponens.

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