Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq and deferred evaluation

When you use LINQ to define an enumerable collection, either by using the LINQ extension methods or by using query operators,the application does not actually build the collection at the time that the LINQ extension method is executed; the collection is enumerated only when you iterate over it. This means that the data in the original collection can change between executing a LINQ query and retrieving the data that the query identifies; you will always fetch the most up-to-date data.

Microsoft Visual C# 2013 step by step written by John Sharp

I have written the following code:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<int> res = numbers.FindAll(a => a > 0).Select(b => b).ToList();
numbers.Add(99);
foreach (int item in res)
    Console.Write(item + ", ");

The result of the above code is shown bellow:

1, 2, 3, 4, 5,

Why is that going like this? I know about Func, Action and Predicate but I can not figure out what is going on here. Based on the above definition the code is not rational.

like image 462
Green Falcon Avatar asked Aug 17 '16 18:08

Green Falcon


1 Answers

Apart from the ToList() at the end, which is creating a new collection, you have another issue.

The problem is that you are not using LINQ at all.

FindAll is not a LINQ extension method.

You should use Where:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<int> res = numbers.Where(a => a > 0);

numbers.Add(99);

foreach (int item in res)
    Console.Write(item + ", ");
like image 50
Matias Cicero Avatar answered Oct 19 '22 19:10

Matias Cicero