LINQでこれを行うにはどうすればよいですか?
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 )
注文は 1 日 1 回だけなので、重複の心配はありません。
LINQ の左結合まで到達しましたが、サブクエリをどこにどのように配置するかがわかりません。
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
};
最終的解決:
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
};
ラムダを使用しない別のソリューション
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
};