Example of Linq Delayed Query in C

  • 2021-06-29 11:50:12
  • OfStack

Ask questions

The code given below compiles normally, but there are errors when it executes, indicating which line of code numbered (1) (2) (3) the program can execute on at execution time.


using System;
using System.Collections.Generic;
using System.Linq;
namespace DeferredExecutionExp
{
  class Program
  {
    static void Main(string[] args)
    {
      List<Student> studentList = new List<Student>()
      {
        new Student(){Id =1, Name="ZhangSan", Age=20},
        new Student(){Id =2, Name=null, Age=21},
        new Student(){Id =3, Name="Lisi", Age=22}
      };
      var queryedStudentList = studentList.Where(it => it.Name.Trim() != "ZhangSan");//(1)
      if (queryedStudentList.Count() > 0)//(2)
      {
        foreach (var student in queryedStudentList)//(3)
        {
          Console.WriteLine(student.Name);
        }
      }
    }
  }
  public class Student
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
  }
}

problem analysis

In fact, it is not difficult to find problems, it is clear that the code "it = > An error occurs when it.Name.Trim()"because the Name attribute of the second student in the set studentList is null. It is not surprising that when the student is traversed, the Trim operation is performed on his Name attribute.Since there will be errors here, the program must execute to this line on GameOver.But will that be the case?

Manual Validation

Step-by-step debugging of the program, found that: when the code line (1) is executed, the program did not make an error, but when the code line (2) is executed, the program only has an exception, check the exception information, but prompt that there is a problem in executing the code line (1). Why?Why is line (1) executed when it reaches line (2)?This is all due to delayed queries from Linq.

Delayed Query

Delayed query means that when a query expression is defined at run time, the query will not execute and will only execute when iterating over data items.The code line (1) in this example simply defines a query, while the data item is traversed when the Count method is called in the code line (2), and the query is executed, that is, the query defined by the code line (1), which ultimately leads to this phenomenon in this example.

So the line of code that the code in this example ultimately executes is (2).


Related articles: