Reputation: 1385
Consider following code:
class Program
{
public static ObservableCollection<Foo> collection = new ObservableCollection<Foo>();
static void Main(string[] args)
{
Foo bar = null;
var result1 = collection.Where(b => b.id == bar.id).FirstOrDefault();
var result2 = collection.Where(c => c.id == bar.id).ToList();
}
public class Foo
{
public string id;
}
}
This code runs smoothly. result1
is null
, and result2 is an empty List<Foo>
.
If collection has elements, then exceptions are thrown, as expected. So I guess, that expressions are not evaluated if collection doesn't have elements.
In case of FirstOrDefault
it is acceptable, since one should handle null return anyway, but in case of querying for multiple elements I find this behaviour confusing, since I can be unaware of what elements are in collection, if there is any, and pass an unitialised object in lambda by mistake, but get the somewhat "correct" result i.e. empty List<Foo>
Can linq expression be evaluated when collection is emty, to prevent getting unexpected result and get exception instead?
Upvotes: 0
Views: 86
Reputation: 203820
The predicate to Where
is called for every element in the collection (if the entire result set is iterated). So Where
is absolutely executing on an empty collection, it's just not calling the predicate. It's calling it on all zero of the items in the collection.
It is of course true that a predicate that doesn't actually work cannot be adequately tested by calling it on an empty collection. To test that the predicate is working you'll need to have at least some of your tests have actual items in the sequence for the predicate to be called on.
Upvotes: 3