C#中使用LINQ和lambda實(shí)現(xiàn)左鏈接私杜、右鏈接、內(nèi)鏈接
在 C# 中使用 LINQ 和 lambda 表達(dá)式可以實(shí)現(xiàn)左鏈接(Left Join)救欧、右鏈接(Right Join)和內(nèi)鏈接(Inner Join)操作衰粹。這些鏈接操作是針對(duì)兩個(gè)數(shù)據(jù)集合之間的關(guān)聯(lián)查詢(xún),用于獲取滿(mǎn)足特定條件的匹配項(xiàng)笆怠。下面是使用 LINQ 和 lambda 表達(dá)式分別實(shí)現(xiàn)這些鏈接操作的示例:
假設(shè)我們有兩個(gè)數(shù)據(jù)集合:orders
和 customers
铝耻,并且它們之間有一個(gè)共同的屬性 CustomerId
。
- 左鏈接(Left Join):
左鏈接返回兩個(gè)集合中的所有元素蹬刷,并且還包括滿(mǎn)足指定條件的匹配項(xiàng)瓢捉。如果右側(cè)的集合沒(méi)有匹配項(xiàng)频丘,將使用默認(rèn)值表示。
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 表達(dá)式:
var leftJoinQuery = customers.GroupJoin(
orders,
customer => customer.CustomerId,
order => order.CustomerId,
(customer, customerOrders) => new
{
customer.CustomerName,
OrderId = customerOrders.Select(co => co?.OrderId ?? 0).FirstOrDefault()
}
);
- 右鏈接(Right Join):
右鏈接返回兩個(gè)集合中的所有元素泡态,并且還包括滿(mǎn)足指定條件的匹配項(xiàng)搂漠。如果左側(cè)的集合沒(méi)有匹配項(xiàng),將使用默認(rèn)值表示兽赁。
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 表達(dá)式:
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
}
);
- 內(nèi)鏈接(Inner Join):
內(nèi)鏈接返回兩個(gè)集合中滿(mǎn)足指定條件的匹配項(xiàng)状答。
var innerJoinQuery = from order in orders
join customer in customers on order.CustomerId equals customer.CustomerId
select new { customer.CustomerName, order.OrderId };
使用 Lambda 表達(dá)式:
var innerJoinQuery = orders.Join(
customers,
order => order.CustomerId,
customer => customer.CustomerId,
(order, customer) => new { customer.CustomerName, order.OrderId }
);
以上是使用 LINQ 和 lambda 表達(dá)式實(shí)現(xiàn)左鏈接、右鏈接和內(nèi)鏈接操作的示例刀崖。通過(guò)掌握這些查詢(xún)技巧惊科,你可以更靈活地處理數(shù)據(jù)集合之間的關(guān)聯(lián)查詢(xún)。