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表达式,适合复杂的查询。
  • 两种语法在功能上是等价的,选择哪种语法取决于个人偏好和查询的复杂性。
相关推荐
杨杨杨大侠几秒前
05 - 上下文管理机制 📦
后端·workflow
杨杨杨大侠1 分钟前
06 - 表达式引擎实现 🔍
后端·workflow
AAA修煤气灶刘哥1 分钟前
日志排查不用慌!从采集到 ELK 实战,手把手教你搞定线上问题
后端·面试·debug
就是帅我不改2 分钟前
SpringBoot多租户架构设计终极指南:5种方案彻底解决企业级SaaS隔离难题
后端·面试·架构
aloha_7 分钟前
Hibernate 继承关系
后端
叫我阿柒啊17 分钟前
自学渗透,学会五分钟安装DVWA漏洞靶场
后端·安全
卓伊凡24 分钟前
复杂项目即时通讯从android 5升级android x后遗症之解决报错#6 java.net.SocketException Software caused
前端·后端
PineappleCoder26 分钟前
同源策略是啥?浏览器为啥拦我的跨域请求?(一)
前端·后端·node.js
用户67570498850243 分钟前
gRPC凭什么成为微服务通信首选?深度解析RPC进化史
后端
华仔啊1 小时前
3行注解干掉30行日志代码!Spring AOP实战全程复盘
java·spring boot·后端