IEnumerable and .Where Linq method behaviour?

前端 未结 2 1376
南旧
南旧 2021-01-17 21:25

I thought I know everything about IEnumerable but I just met a case that I cannot explain. When we call .Where linq method on a IEnumerable

相关标签:
2条回答
  • 2021-01-17 22:07

    Like many LINQ operations, Select is lazy and use deferred execution so your lambda expression is never being executed, because you're calling Select but never using the results. This is why, everything work fine after calling .ToList() just after calling GenerateEnumerableTest() method:

    var tab = CTest.GenerateEnumerableTest().ToList();
    
    0 讨论(0)
  • 2021-01-17 22:08
    var tab = CTest.GenerateEnumerableTest();
    

    This tab is a LINQ query that generates CTest instances that are initialized from int-values which come from an integer array which will never change. So whenever you ask for this query you will get the "same" instances(with the original Amount).

    If you want to "materialize" this query you could use ToList and then change them. Otherwise you are modifying CTest instances that exist only in the first foreach loop. The second loop enumerates other CTest instances with the unmodified Amount.

    So the query contains the informations how to get the items, you could also call the method directly:

    foreach (var item in CTest.GenerateEnumerableTest().Where(i => i.Amount > 6))
    {
        item.Amount = item.Amount * 2;
    }
    
    foreach (var t in CTest.GenerateEnumerableTest())
    {
       // now you don't expect them to be changed, do you?
    }
    
    0 讨论(0)
提交回复
热议问题