Could you explain on the following example what a deferred execution is and what materialization is? What will the output be?
string[] animals = { "dog", "cat", "crocodile", "Peter" };
var list = new List<string>(animals);
IEnumerable<string> query = list.Where(p => p.Length == 5);
list.Remove("Peter");
Console.WriteLine(query.Count());
Experience Level: Medior
Tags: .NETC#LINQPerformance
Answer
- The string array animals is initialized.
- New list of strings is created from the array using generic List<string> class.
- The query that matches all list items that have length 5 is assigned to the query variable. It's however not executed. The execution is deferred.
- The item "Peter" is removed from the list, which is perfectly valid.
- The call to .Count() will execute the evaluation of the query. The query execution was deferred until now but will be processed now.
- When the query gets evaluated, no items with length 5 exist in the list so 0 will be written as the output to the console.
- Deferred execution is a term describing the fact, that the LINQ query is not executed immediatelly, but later.
- Materializaton is the process of query evaluation and conversion to the real values (usually executed by iteration, .ToList(), .ToArray(), .Count() etc.)
Related C# job interview questions
Do you use generics? What are they good for? And what are constraints and why to use them?
.NETC#Performance MediorCould you explain what the following LINQ methods OrderBy, Where and Single do and what will be the output of the code?
.NETC#LINQ JuniorWhat array initialization syntaxes do you know?
.NETC# MediorHow does the .Max(...) work in LINQ? What will be the result of the following code?
.NETC#LINQ JuniorWhat is a difference between partial class and partial method and what are they good for?
.NETC# Senior