c# - Why is IEnumerable.Count() reevaluating the query? -


the following code prints "2 2 2 2" when expect "1 1 1 1". why "count()" reevaluates query?

class class1 {     static int globaltag = 0;      public class1()     {         tag = (++globaltag);     }      public int tag;      public int calls = 0;      public int do()     {         calls++;         return tag;     } }  class program {     static void main(string[] args)     {         class1[] cls = new class1[] { new class1(), new class1(), new class1(), new class1() };          var result = cls.where(c => (c.do() % 2) == 0);         if (result.count() <= 10)         {             if (result.count() <= 10)             {                 foreach (var c in cls)                 {                     console.writeline(c.calls);                 }             }         }     } } 

how else work? expect count() in order cache values?

linq objects executes lazily, evaluating query when needs - such count elements. call where isn't evaluating sequence @ all; remembers predicate , sequence can evaluate when needs to.

for lot more details how linq objects works, suggest read edulinq blog series. it's rather long (and not quite finished) it'll give lot more insight how linq objects works.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -