Junior — Middle
Kas saaksite selgitada LINQ-s tulemuste hilinenud initsialiseerimise kontseptsiooni ja kuidas see töötab?
sobes.tech AI
Vastus AI-lt
In LINQ (Language Integrated Query) in C# the concept of deferred (lazy) initialization or deferred execution of queries is used. This means that the query itself on the collection is not executed at the moment of its declaration, but only when the result is accessed, for example, during iteration in a loop or when calling methods that require materialization (e.g., ToList(), ToArray()).
Deferred execution allows:
- Optimizing performance, as queries are not executed unnecessarily.
- Building complex query chains that will be executed in a single pass.
Example:
var numbers = new List<int> {1, 2, 3, 4, 5};
var query = numbers.Where(n => n > 3); // Query declared but not executed
foreach(var num in query) // Query is executed here
{
Console.WriteLine(num); // Will output 4 and 5
}
If we modify the collection numbers after declaring the query but before executing it, the result would change, because the query is executed exactly at the moment of iteration.