软件编程
位置:首页>> 软件编程>> C#编程>> C#中Linq延迟查询的例子

C#中Linq延迟查询的例子

作者:junjie  发布时间:2022-01-15 02:43:11 

标签:C#,Linq,延迟查询

提出问题

下面所给代码编译时正常,但是执行时会出错,请指出程序在执行时能够执行到编号为(1)(2)(3)的代码行中的哪一行。


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; }
 }
}

问题分析

其实,发现问题并不难,很显然在执行代码“it => it.Name.Trim()”时会出错,因为集合studentList中第二个学生的Name属性为null,当遍历到该学生时,对其Name属性执行Trim操作,不出错才怪呢。既然在这里会出错,那么程序肯定是执行到该行就GameOver了呀。但是实际情况又会是这样吗?

动手验证

单步调试程序,发现:执行到代码行(1)时,程序并没有出错,而是在执行代码行(2)时,程序才出现了异常,查看异常信息,却提示的是在执行代码行(1)时有问题,为什么会这样呢?为什么执行到代码行(2)时还会去执行代码行(1)呢?这全都是因为Linq的延迟查询导致的。

延迟查询

延迟查询的意思是说:在运行期间定义查询表达式时,查询不会执行,只有到迭代数据项时查询才会被执行。本例中的代码行(1)只是定义了查询,而代码行(2)中当调用Count方法时便会遍历数据项,这时便会执行查询,也就是说会去执行代码行(1)定义的查询,最终导致了本例中这种现象的出现。

所以,本例中的代码最终能够执行到的代码行是(2)。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com