C# linq 查询语法与方法语法示例

在C#中,LINQ(Language Integrated Query)提供了两种查询语法:查询语法 (Query Syntax)和方法语法(Method Syntax)。两种语法在功能上是等价的,最终都会被编译器转换为方法调用。以下是两种语法的对比示例。


1. 查询语法(Query Syntax)

查询语法类似于SQL,使用 fromwhereselect 等关键字,适合简单的查询。

示例:

假设有一个 Students 集合,我们想查询年龄大于20的学生

c# 复制代码
var query = from student in Students
            where student.Age > 20
            select student;

说明:

  • from:指定数据源。
  • where:过滤条件。
  • select:选择要返回的数据。

2. 方法语法(Method Syntax)

方法语法使用扩展方法(如 WhereSelect 等)和Lambda表达式,适合复杂的查询。

示例:

同样的查询,使用方法语法实现。

C# 复制代码
var query = Students
    .Where(student => student.Age > 20)
    .Select(student => student);

说明:

  • Where:过滤条件。
  • Select:选择要返回的数据。
  • Lambda表达式 student => student.Age > 20 用于定义过滤条件。

3. 两种语法的对比示例

示例1:简单查询

查询所有年龄大于20的学生姓名。

查询语法:

C# 复制代码
var query = from student in Students
            where student.Age > 20
            select student.Name;

方法语法:

C# 复制代码
var query = Students
    .Where(student => student.Age > 20)
    .Select(student => student.Name);

示例2:排序

查询所有年龄大于20的学生,并按年龄升序排序。

查询语法:

C# 复制代码
var query = from student in Students
            where student.Age > 20
            orderby student.Age
            select student;

方法语法:

C# 复制代码
var query = Students
    .Where(student => student.Age > 20)
    .OrderBy(student => student.Age);

示例3:分组

按学生的年龄分组,并统计每组的学生数量。

查询语法:

C# 复制代码
var query = from student in Students
            group student by student.Age into ageGroup
            select new
            {
                Age = ageGroup.Key,
                Count = ageGroup.Count()
            };

方法语法:

C# 复制代码
var query = Students
    .GroupBy(student => student.Age)
    .Select(ageGroup => new
    {
        Age = ageGroup.Key,
        Count = ageGroup.Count()
    });

示例4:连接(JOIN)

假设有两个集合:StudentsCourses,查询学生和他们所选的课程。

查询语法:

C# 复制代码
var query = from student in Students
            join course in Courses
            on student.CourseId equals course.Id
            select new
            {
                StudentName = student.Name,
                CourseName = course.Name
            };

方法语法:

C# 复制代码
var query = Students
    .Join(Courses,
          student => student.CourseId,
          course => course.Id,
          (student, course) => new
          {
              StudentName = student.Name,
              CourseName = course.Name
          });

示例5:左连接(LEFT JOIN)

查询所有学生,即使他们没有选课。

查询语法:

C# 复制代码
var query = from student in Students
            join course in Courses
            on student.CourseId equals course.Id into studentCourses
            from sc in studentCourses.DefaultIfEmpty()
            select new
            {
                StudentName = student.Name,
                CourseName = sc?.Name ?? "No Course"
            };

方法语法:

C# 复制代码
var query = Students
    .GroupJoin(Courses,
               student => student.CourseId,
               course => course.Id,
               (student, courses) => new { student, courses })
    .SelectMany(
        x => x.courses.DefaultIfEmpty(),
        (student, course) => new
        {
            StudentName = student.student.Name,
            CourseName = course?.Name ?? "No Course"
        });

4. 两种语法的选择

  • 查询语法:适合简单的查询,尤其是当查询条件较少且逻辑简单时,代码更易读。
  • 方法语法:适合复杂的查询和操作,尤其是当需要链式调用多个方法时,代码更灵活。

总结

  • 查询语法 :类似于SQL,使用 fromwhereselect 等关键字。
  • 方法语法:使用扩展方法和Lambda表达式,适合复杂的查询。
  • 两种语法在功能上是等价的,选择哪种语法取决于个人偏好和查询的复杂性。
相关推荐
Honmaple5 分钟前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东24 分钟前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble33 分钟前
springboot的核心实现机制原理
java·spring boot·后端
wfserial35 分钟前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
全栈老石1 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
space62123271 小时前
在SpringBoot项目中集成MongoDB
spring boot·后端·mongodb
Tony Bai2 小时前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang
阔皮大师2 小时前
INote轻量文本编辑器
java·javascript·python·c#
寻找奶酪的mouse2 小时前
30岁技术人对职业和生活的思考
前端·后端·年终总结
梦想很大很大2 小时前
使用 Go + Gin + Fx 构建工程化后端服务模板(gin-app 实践)
前端·后端·go