Register to Better Coder! It's free.
Enjoy the premium features and succeed at every job interview.

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

  1. The string array animals is initialized.
  2. New list of strings is created from the array using generic List<string> class.
  3. 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.
  4. The item "Peter" is removed from the list, which is perfectly valid.
  5. The call to .Count() will execute the evaluation of the query. The query execution was deferred until now but will be processed now.
  6. 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.)

Comments

No Comments Yet.
Be the first to tell us what you think.