如何在lambda表达式中编写LINQ Join命令
本文关键字:LINQ Join 命令 lambda 表达式 | 更新日期: 2023-09-27 18:17:38
我在LINQ中编写了以下JOIN语句:
var result = (from od in orders
join em in employees on od.EmployeeID equals em.EmployeeID
join ct in customers on od.CustomerID equals ct.CustomerID
select new MyJoin
{
OrderID = od.OrderID,
//OrderDate = od.OrderDate,
ShipCountry = od.ShipCountry,
CompanyName = ct.CompanyName,
ContactName = ct.ContactName,
EmployeeName = (em.FirstName + ' '+em.LastName),
})
我如何将其写成lambda表达式?
我提供ReSharper-as-a-Service:
var result = orders.Join(employees,
od => od.EmployeeID,
em => em.EmployeeID,
(od, em) => new { od, em })
.Join(customers,
od => od.CustomerID,
ct => ct.CustomerID,
(obj, ct) => new MyJoin
{
OrderID = obj.od.OrderID,
OrderDate = obj.od.OrderDate,
ShipCountry = obj.od.ShipCountry,
CompanyName = ct.CompanyName,
ContactName = ct.ContactName,
EmployeeName = (obj.em.FirstName + ' ' + obj.em.LastName),
});
您正在使用Join
扩展方法:
IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
this IEnumerable<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, TInner, TResult> resultSelector);
对于第一个调用,这是它与上面的LINQ语法的关系:
outer: orders
inner: employees
outerKeySelector: od.EmployeeID
innerKeySelector: em.EmployeeID
resultSelector: <this is implied in your LINQ statements>
将outerKeySelector
和innerKeySelector
与您的LINQ中equals
的效果进行比较。