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

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

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

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

  1. 左链接(Left Join):

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

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 表达式:

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):

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

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 表达式:

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):

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

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

使用 Lambda 表达式:

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

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

猜你喜欢

转载自blog.csdn.net/qq_36799389/article/details/131904151