我在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表达式?
答案 0 :(得分:0)
我提供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
的效果进行比较。