SoFunction
Updated on 2025-03-06

Example of Linq delay query in C#

Ask a question

The code given below is normal when compiling, but an error occurs during execution. Please indicate which line of code numbered (1) (2) (3) can be executed.

using System;
using ;
using ;
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 = (it => () != "ZhangSan");//(1)
      if (() > 0)//(2)
      {
        foreach (var student in queryedStudentList)//(3)
        {
          ();
        }
      }
    }
  }
  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 the problem. Obviously, an error occurs when executing the code "it => ()", because the Name attribute of the second student in the collection studentList is null. When traversing the student, perform a Trim operation on its Name attribute. It would be strange if there is no error. Since an error occurs here, the program must be GameOver when it is executed in that line. But is this the reality?

Hands-on verification

When debugging the program step by step, I found that when the code line (1), the program did not make any errors, but when the code line (2), the program only had an exception. I checked the exception information, but it prompted that there was a problem when executing the code line (1). Why is this happening? Why do you still execute lines of code (1) when executing lines of code (2)? This is all caused by Linq's delayed query.

Delayed query

Delayed query means: when defining a query expression during runtime, the query will not be executed, and the query will only be executed when iterates over the data items. The line of code (1) in this example only defines the query, and in line of code (2), the data items will be traversed when the Count method is called, and the query will be executed, that is, the query defined by line of code (1) will be executed, which ultimately leads to the occurrence of this phenomenon in this example.

Therefore, the line of code that the code in this example can be executed in the end is (2).