C# linq 各种连接方法示例(如左连接,右连接)

在C#中,LINQ(Language Integrated Query)提供了多种连接操作,类似于SQL中的JOIN操作。常见的连接操作包括内连接左连接右连接全外连接。以下是这些连接操作的示例。


1. 内连接(INNER JOIN)

内连接返回两个集合中满足连接条件的元素。

查询语法

示例:

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

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

方法语法:

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

2. 左连接(LEFT JOIN)

左连接返回左集合中的所有元素,即使右集合中没有匹配的元素。如果右集合中没有匹配的元素,则返回默认值。

查询语法

示例:

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

C# 复制代码
var leftJoinQuery = 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 leftJoinQuery = 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"
        });

3. 右连接(RIGHT JOIN)

右连接返回右集合中的所有元素,即使左集合中没有匹配的元素。如果左集合中没有匹配的元素,则返回默认值。

LINQ本身没有直接的右连接操作,但可以通过交换左连接中的集合来实现。

查询语法

示例:

查询所有课程,即使没有学生选修。

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

方法语法:

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

4. 全外连接(FULL OUTER JOIN)

全外连接返回左集合和右集合中的所有元素。如果某一边没有匹配的元素,则返回默认值。

LINQ没有直接支持全外连接,但可以通过组合左连接和右连接来实现。

查询语法

示例:

查询所有学生和课程,包括没有选课的学生和没有学生的课程。

c# 复制代码
var leftJoin = 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"
               };

var rightJoin = from course in Courses
                join student in Students
                on course.Id equals student.CourseId into courseStudents
                from cs in courseStudents.DefaultIfEmpty()
                select new
                {
                    StudentName = cs?.Name ?? "No Student",
                    CourseName = course.Name
                };

var fullOuterJoin = leftJoin.Union(rightJoin);

5. 交叉连接(CROSS JOIN)

交叉连接返回两个集合的笛卡尔积,即左集合中的每个元素与右集合中的每个元素组合。

查询语法

示例:

查询所有学生和课程的所有可能组合。

C# 复制代码
var crossJoinQuery = from student in Students
                     from course in Courses
                     select new
                     {
                         StudentName = student.Name,
                         CourseName = course.Name
                     };

方法语法:

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

总结

  • 内连接 :使用 join 关键字或 Join 方法。
  • 左连接 :使用 GroupJoinDefaultIfEmpty
  • 右连接:通过交换左连接的集合实现。
  • 全外连接:通过组合左连接和右连接实现。
  • 交叉连接 :使用 SelectMany 或嵌套 from 子句。

这些连接操作可以帮助你在LINQ中实现复杂的查询逻辑,类似于SQL中的JOIN操作。

相关推荐
XMYX-02 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
CoderIsArt2 小时前
C#中的CLR属性、依赖属性与附加属性
c#
@yanyu6664 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码4 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智5 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货5 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫5 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
写bug写bug6 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
不超限6 小时前
Asp.net core 使用EntityFrame Work
后端·asp.net