Lambda 是一个有用的东西,但对我来说也有点令人困惑。有人可以在没有 lambda 的情况下执行 linq'WHERE' 查询吗,这样我就可以理解发生了什么。
List<Student> st = new List<Student>() {
new Student(){Id=1,Name="Nav"},
new Student(){Id=2,Name="San"},
new Student(){Id=3,Name="Jat"},
};
Student? me = st.Where(st => st.Name == "Nav").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
我想看看如何在没有 lambda 的情况下做到这一点。
首先,lambda 是一种非常强大且常用的工具.net,LINQ因此学习如何阅读和理解它们非常有用。C# 中的 Lambda 表达式允许您编写简洁且富有表现力的代码,使您的代码更具可读性和更容易理解。
在您的代码中,我们使用类Where的方法List<T>以及 lambda 表达式来过滤学生列表并获取Name属性匹配的学生"Nav"。
下面是如何在不使用 lambda 表达式和 LINQ 的情况下获得相同结果的示例:
var st = new List<Student>() {
new Student(){ Id = 1, Name = "Nav" },
new Student(){ Id = 2, Name = "San" },
new Student(){ Id = 3, Name = "Jat" },
};
Student firstOrDefaultStudent = null;
foreach (Student s in st)
{
// if is analog for where
// we compare the Name property of each student with the string "Nav".
// When we find a student whose Name property matches "Nav",
// we assign that student to the variable "firstOrDefaultStudent"
if (s.Name == "Nav")
{
firstOrDefaultStudent = s;
// this is analog for first or default
// when we find first matched value we stop our loop
// because we need only first student that matches condition
break;
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以用方法替换您的 lambda。将为集合中的每个项目调用此方法并返回一个bool值,该值表示该项目是否符合该方法中描述的条件。
var st = new List<Student>() {
new Student(){ Id = 1, Name = "Nav" },
new Student(){ Id = 2, Name = "San" },
new Student(){ Id = 3, Name = "Jat" },
};
Student? me = st.Where(IsNameEqualsToNav).FirstOrDefault();
private static bool IsNameEqualsToNav(Student st)
{
return st.Name == "Nav";
}
Run Code Online (Sandbox Code Playgroud)
请记住另一个重要的 LINQ 行为。LINQ 操作通常使用延迟执行来实现:
延迟执行意味着表达式的计算被延迟,直到实际需要其实现的值为止。当您必须操作大型数据集合时,尤其是在包含一系列链接查询或操作的程序中,延迟执行可以极大地提高性能。在最好的情况下,延迟执行仅允许对源集合进行一次迭代。
LINQ 技术在核心 System.Linq 类的成员和各种 LINQ 命名空间(例如 System.Xml.Linq.Extensions)的扩展方法中广泛使用延迟执行。