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.
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 + ", ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With