2012-05-08 13 views
10

LINQでこれを行うにはどうすればよいですか?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 
      }; 

答えて

13

これは多かれ少なかれリテラルな翻訳です

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 
      }; 

が、私は

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

ありがとう、リテラルトランスレーションに基づいた最終的なソリューションです。 – mfc

1

に書き換えますどのようにあなたのためにこの作品?

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 
    }; 
関連する問題