Linq表达式中Inner join(内链接)和left join、right join 的区别

废话不多说直接上代码演示:

接下来,定义 OrderCustomer 类,以及一些示例数据

using System;
using System.Linq;
using System.Collections.Generic;

class Order
{
    public int OrderId { get; set; }
    public string OrderName { get; set; }
    public int CustomerId { get; set; }
}

class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
}
//创建两个表 用CustomerId 为关联条件
var orders = new List<Order>
{
    new Order { OrderId = 1, OrderName = "Ordername 1", CustomerId = 1001 },
    new Order { OrderId = 2, OrderName = "Ordername 2", CustomerId = 1002 },
    new Order { OrderId = 3, OrderName = "Ordername 3", CustomerId = 1003 },
};

var customers = new List<Customer>
{
    new Customer { CustomerId = 1001, CustomerName = "Alice" },
    new Customer { CustomerId = 1003, CustomerName = "Bob" },
};

内连接示例

var innerJoinQuery =
    from order in orders
    join customer in customers
    on order.CustomerId equals customer.CustomerId
    select new
    {
        OrderName = order.OrderName,
        CustomerName = customer.CustomerName
    };

Console.WriteLine("Inner Join Results:");
foreach (var result in innerJoinQuery)
{
    Console.WriteLine($"Order: {result.OrderName}, Customer: {result.CustomerName}");
}

上述代码将执行内连接操作,只返回匹配的数据。结果只包括 orderscustomers 中具有相同 CustomerId 的行。

左连接示例:

var leftJoinQuery =
    from order in orders
    join customer in customers
    on order.CustomerId equals customer.CustomerId into customerGroup
    from customer in customerGroup.DefaultIfEmpty()
    select new
    {
        OrderName = order.OrderName,
        CustomerName = (customer != null) ? customer.CustomerName : "N/A"
    };

Console.WriteLine("\nLeft Join Results:");
foreach (var result in leftJoinQuery)
{
    Console.WriteLine($"Order: {result.OrderName}, Customer: {result.CustomerName}");
}

上述代码将执行左连接操作,返回了 orders 表的所有行,以及与之匹配的 customers 行(如果有匹配的话)。如果没有匹配的话,CustomerName 将标记为 "N/A"。

右连接示例:

var rightJoinQuery =
    from customer in customers
    join order in orders
    on customer.CustomerId equals order.CustomerId into orderGroup
    from order in orderGroup.DefaultIfEmpty()
    select new
    {
        CustomerName = customer.CustomerName,
        OrderName = (order != null) ? order.OrderName : "N/A"
    };

Console.WriteLine("Right Join Results:");
foreach (var result in rightJoinQuery)
{
    Console.WriteLine($"Customer: {result.CustomerName}, Order: {result.OrderName}");
}

上述代码模拟了 right join 操作,返回了 customers 表的所有行,以及与之匹配的 orders 行(如果有匹配的话)。如果没有匹配的话,OrderName 将标记为 "N/A"。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值