I have an IEnumerable<T>
that I wanted to filter based on a LINQ predicate. I tried using Where
on the IEnumerable
as I normally do, but this time I stumbled upon something interesting. When calling Where on the IEnumerable
, with the predicate, i get an empty list in return. I know it has to produce a list with two items in it. If I instead use FindAll
, with the same predicate, it then produces the correct result.
Can anyone explain to me, why this is happening? I always thought that Where
was kind of a lazy version of FindAll
, that also returned an IEnumerable
instead of a List
. There must be more to it than that? (I have done some research, but to no avail.)
Code:
IEnumerable<View> views = currentProject.Views.Where(
v => v.Entries.Any(e => e.Type == InputType.IMAGE || e.Type == InputType.VIDEO));
IEnumerable<View> views = currentProject.Views.FindAll(
v => v.Entries.Any(e => e.Type == InputType.IMAGE || e.Type == InputType.VIDEO));
You can find your answer here: LINQ, Where() vs FindAll() . Basically if you call .ToList() on your "Where" they would be the same.
You can find more about the differences between deferred and immediate execution: https://code.msdn.microsoft.com/LINQ-Query-Execution-ce0d3b95
My best guess would be that something happens between calling Where, which creates an enumerator and the place in your code where the results are actually used (i.e. where MoveNext and (get_)Current of that enumerator are actually called, e.g. from ToList).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With