C#中使用LINQ和lambda实现左链接、右链接、内链接

C#中使用LINQ和lambda实现左链接、右链接、内链接

在 C# 中使用 LINQ 和 lambda 表达式可以实现左链接(Left Join)、右链接(Right Join)和内链接(Inner Join)操作。这些链接操作是针对两个数据集合之间的关联查询,用于获取满足特定条件的匹配项。下面是使用 LINQ 和 lambda 表达式分别实现这些链接操作的示例:

假设我们有两个数据集合:orderscustomers,并且它们之间有一个共同的属性 CustomerId

  1. 左链接(Left Join):

左链接返回两个集合中的所有元素,并且还包括满足指定条件的匹配项。如果右侧的集合没有匹配项,将使用默认值表示。

csharp 复制代码
var leftJoinQuery = from customer in customers
                    join order in orders on customer.CustomerId equals order.CustomerId into customerOrders
                    from co in customerOrders.DefaultIfEmpty()
                    select new { customer.CustomerName, OrderId = co?.OrderId ?? 0 };

使用 Lambda 表达式:

csharp 复制代码
var leftJoinQuery = customers.GroupJoin(
    orders,
    customer => customer.CustomerId,
    order => order.CustomerId,
    (customer, customerOrders) => new
    {
        customer.CustomerName,
        OrderId = customerOrders.Select(co => co?.OrderId ?? 0).FirstOrDefault()
    }
);
  1. 右链接(Right Join):

右链接返回两个集合中的所有元素,并且还包括满足指定条件的匹配项。如果左侧的集合没有匹配项,将使用默认值表示。

csharp 复制代码
var rightJoinQuery = from order in orders
                     join customer in customers on order.CustomerId equals customer.CustomerId into orderCustomers
                     from oc in orderCustomers.DefaultIfEmpty()
                     select new { CustomerName = oc?.CustomerName ?? "N/A", order.OrderId };

使用 Lambda 表达式:

csharp 复制代码
var rightJoinQuery = orders.GroupJoin(
    customers,
    order => order.CustomerId,
    customer => customer.CustomerId,
    (order, orderCustomers) => new
    {
        CustomerName = orderCustomers.Select(oc => oc?.CustomerName ?? "N/A").FirstOrDefault(),
        order.OrderId
    }
);
  1. 内链接(Inner Join):

内链接返回两个集合中满足指定条件的匹配项。

csharp 复制代码
var innerJoinQuery = from order in orders
                     join customer in customers on order.CustomerId equals customer.CustomerId
                     select new { customer.CustomerName, order.OrderId };

使用 Lambda 表达式:

csharp 复制代码
var innerJoinQuery = orders.Join(
    customers,
    order => order.CustomerId,
    customer => customer.CustomerId,
    (order, customer) => new { customer.CustomerName, order.OrderId }
);

以上是使用 LINQ 和 lambda 表达式实现左链接、右链接和内链接操作的示例。通过掌握这些查询技巧,你可以更灵活地处理数据集合之间的关联查询。

相关推荐
Sinclair14 小时前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
Scout-leaf14 小时前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户2986985301417 小时前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
茶杯梦轩2 天前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
mudtools2 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的2 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21882 天前
.NET 本地Db数据库-技术方案选型
windows·c#
海天鹰2 天前
【免费】PHP主机=域名+解析+主机
服务器
lindexi2 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice