如何在lambda表达式中编写LINQ Join命令

时间:2015-10-13 10:59:59

标签: c# linq lambda

我在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表达式?

1 个答案:

答案 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>

outerKeySelectorinnerKeySelector与来自LINQ的equals的效果进行比较。