2012-05-08 9 views
10

Come posso farlo in LINQ?LINQ; come ottenere record con la data massima con l'adesione?

select 
    * 
from customer c 
left join order o on o.CustomerID = c.CustomerID 
where o.OrderDate = (select MAX(OrderDate) from order where CustomerID = o.CustomerID) 

non preoccupato per i doppi perché ci sarà sempre un solo ordine al giorno.

ho ottenuto per quanto riguarda la sinistra unisco a LINQ, ma non è sicuro come o dove mettere la subquery in

var query = from customer in clist 
      from order in olist 
       .Where(o => o.CustomerID == customer.CustomerID) 
      select new { 
       customer.CustomerID, 
       customer.Name, 
       customer.Address, 
       Product = order != null ? order.Product : string.Empty 
      }; 

soluzione finale:.

var query = from customer in clist 
      from order in olist 
      .Where(o => o.CustomerID == customer.CustomerID && o.OrderDate == 
       olist.Where(o1 => o1.CustomerID == customer.CustomerID).Max(o1 => o1.OrderDate) 
      ) 
      select new { 
       customer.CustomerID, 
       customer.Name, 
       customer.Address, 
       order.Product, 
       order.OrderDate 
      }; 

Un'altra soluzione senza alcun lambda

var query = from customer in clist 
      from order in olist 
      where order.CustomerID == customer.CustomerID && order.OrderDate == 
       (from o in olist 
       where o.CustomerID == customer.CustomerID 
       select o.OrderDate).Max() 
      select new { 
       customer.CustomerID, 
       customer.Name, 
       customer.Address, 
       order.Product, 
       order.OrderDate 
      }; 

risposta

13

Questa è più o meno una traduzione letterale

var query = from customer in clist 
      from order in olist 
       .Where(o => o.CustomerID == customer.CustomerID && 
          o.OrderDate == olist 
           .Where(o => o.CustomerID == customer.CustomerID) 
           .Select(o => o.OrderDate).Max()) 
      select new { 
       customer.CustomerID, 
       customer.Name, 
       customer.Address, 
       Product = order != null ? order.Product : string.Empty 
      }; 

ma vorrei riscrivere a

var query = from customer in clist 
      from order in olist 
       .Where(o => o.CustomerID == customer.CustomerID) 
       .OrderByDescending(o => o.OrderDate).Take(1) 
      select new { 
       customer.CustomerID, 
       customer.Name, 
       customer.Address, 
       Product = order != null ? order.Product : string.Empty 
      }; 
+0

Grazie, la mia soluzione finale basata sulla transalazione letterale. – mfc

1

Come funziona questo lavoro per voi?

var query = 
    from customer in clist 
    join order in olist 
     on customer.CustomerID equals order.CustomerID 
     into orders 
    select new 
    { 
     customer.CustomerID, 
     customer.Name, 
     customer.Address, 
     Product = orders 
      .OrderByDescending(x => x.OrderDate) 
      .Select(x => x.Product) 
      .FirstOrDefault() ?? String.Empty 
    }; 
Problemi correlati