Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindAll Vs Where [duplicate]

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));
like image 868
Teilmann Avatar asked Oct 12 '15 09:10

Teilmann


2 Answers

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

like image 91
dlght Avatar answered Sep 28 '22 16:09

dlght


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

like image 45
Primary Key Avatar answered Sep 28 '22 18:09

Primary Key