Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does IQueryable.All() return true on an empty collection?
    text
    copied!<p>So I ran into a situation today where some production code was failing precisely because a method performed exactly as <a href="http://msdn.microsoft.com/en-us/library/bb534754.aspx" rel="noreferrer">documented in MSDN</a>. Shame on me for not reading the documentation. However, I'm still scratching my head as to <em>why</em> it behaves this way, even if "by design", since this behavior is exactly opposite what I would have expected (and other, known behaviors) and therefore seems to violate the principle of least surprise.</p> <p>The <code>All()</code> method allows you to supply a predicate (such as a lambda expression) to test an <code>IQueryable</code>, returning a Boolean value that indicates whether all collection members match the test. So far so good. Here's where it gets weird. <code>All()</code> also returns <code>true</code> if the collection is empty. This seems completely backwards to me, for the following reasons:</p> <ul> <li>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. With this behavior, on an empty driveway all cars parked there are red AND blue AND checkerboard - all of these expressions would return true.</li> <li>For anyone familiar with the SQL notion that NULL != NULL, this is unexpected behavior.</li> <li>The <code>Any()</code> method behaves as expected, and (correctly) returns false because it does not have any members that match the predicate.</li> </ul> <p>So my question is, why does <code>All()</code> behave this way? What problem does it solve? Does this violate the principle of least surprise?</p> <p>I tagged this question as .NET 3.5, though the behavior also applies to .NET 4.0 as well.</p> <p><strong>EDIT</strong> Ok, so I grasp the logic aspect to this, as so excellently laid out by Jason and the rest of you. Admittedly, an empty collection is something of an edge case. I guess my question is rooted in the struggle that, just because something is <em>logical</em> doesn't mean it necessarily makes <em>sense</em> if you're not in the correct frame of mind.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload