C#中Linq延遲查詢的例子
提出問題
下面所給代碼編譯時正常,但是執(zhí)行時會出錯,請指出程序在執(zhí)行時能夠執(zhí)行到編號為(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; } } }
問題分析
其實,發(fā)現(xiàn)問題并不難,很顯然在執(zhí)行代碼“it => it.Name.Trim()”時會出錯,因為集合studentList中第二個學生的Name屬性為null,當遍歷到該學生時,對其Name屬性執(zhí)行Trim操作,不出錯才怪呢。既然在這里會出錯,那么程序肯定是執(zhí)行到該行就GameOver了呀。但是實際情況又會是這樣嗎?
動手驗證
單步調試程序,發(fā)現(xiàn):執(zhí)行到代碼行(1)時,程序并沒有出錯,而是在執(zhí)行代碼行(2)時,程序才出現(xiàn)了異常,查看異常信息,卻提示的是在執(zhí)行代碼行(1)時有問題,為什么會這樣呢?為什么執(zhí)行到代碼行(2)時還會去執(zhí)行代碼行(1)呢?這全都是因為Linq的延遲查詢導致的。
延遲查詢
延遲查詢的意思是說:在運行期間定義查詢表達式時,查詢不會執(zhí)行,只有到迭代數據項時查詢才會被執(zhí)行。本例中的代碼行(1)只是定義了查詢,而代碼行(2)中當調用Count方法時便會遍歷數據項,這時便會執(zhí)行查詢,也就是說會去執(zhí)行代碼行(1)定義的查詢,最終導致了本例中這種現(xiàn)象的出現(xiàn)。
所以,本例中的代碼最終能夠執(zhí)行到的代碼行是(2)。
相關文章
C# Onnx CenterNet實現(xiàn)目標檢測的示例詳解
這篇文章主要為大家詳細介紹了C# Onnx CenterNet實現(xiàn)目標檢測的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-12-12