在我们工作中表连接是很常用的,但常用的有这三种连接方式:左连接、右连接、内链接
在本章节中讲的是
1、如何在Linq中使用左连接,右连接,内连接。
2、三种连接之间的特点在哪?
3、Linq的三种连接语法是怎么样的呢(我觉得左右连接也就相当换个位置)
一、SQL Server 中的三种连接
首先我们示范以下SQL中的左连接,右连接,内连接,需要准备两张表:
CREATE TABLE [dbo].[Company]( [Id] int identity Primary key, [Code] uniqueidentifier, [CompanyName] nvarchar(20) null, [Address] nvarchar(100) null ) CREATE TABLE [dbo].[People]( [Id] int identity Primary key, [CompanyCode] uniqueidentifier null, [Name] nvarchar(20) null, [Age] Int null, )
数据准备
Company
People
在SQL表连接 LEFT JOIN,RIGHT JOIN , INNER JOIN (JOIN)
--通过LEFT JOIN 关键字很明显看出是左连接 SELECT * FROM [People] p LEFT JOIN Company c on p.CompanyCode = c.Code --通过RIGHT JOIN 关键字很明显看出是右连接 SELECT * FROM [Company] c RIGHT JOIN [People] p on p.CompanyCode = c.Code --通过INNER JOIN 关键字很明显看出是内连接 SELECT * FROM [People] p INNER JOIN [Company] c on p.CompanyCode = c.Code
执行后的结果
各连接的特点:
左连接和右连接很好理解,看字面意思就可以知道左连接是按照左边的数据进行显示,如果右边的跟左边的匹配不到则右边的数据会为空,右连接相反
内链接也很好理解,看图可以看出来只要能匹配上的就显示不能匹配的就不显示数据
那么在C# Linq中我们如何实现表连接呢?
二、C# 中使用Linq实现集合之间的连接
同样先准备下类和数据源
Company和People 类
public class Company { public int Id { get; set; } public Guid Code { get; set; } public string CompanyName { get; set; } public string Address { get; set; } } public class People { public int Id { get; set; } public Guid CompanyCode { get; set; } public string Name { get; set; } public int Age { get; set; } }