media media - 3 months ago 11
C# Question

Linq and deferred evaluation

As I have learned LINQ,


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 as follows:

1, 2, 3, 4, 5,


I do not understand why it is going like this. I know about Func, Action and Predicate but I can not figure out what is going on here. Thanks for probable answers. ;)

Answer

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 + ", ");
Comments