2012-08-01 67 views
1

说我有一个名为存储与记录台这种最新日期为sql

Item_Id  | Date   | Price 
1   | 01/01/2011  | 50 
1   | 03/26/2012  | 25 
2   | 04/21/2012  | 20 
3   | 08/02/2012  | 15 
3   | 09/02/2012  | 13 
4   | 10/02/2012  | 18 

我想获得ITEM_ID关联到它的最新日期(在这种情况下,它会接着“ 4“)使用linq to sql。

我用这个表达

var lastDate= Storage 
        .GroupBy(s => s.Item_Id) 
        .Select(grp => new { 
         grp.Key, 
         LastDate = grp.OrderByDescending(
          x => x.Date).First() 
        }).ToList(); 

,我越来越对每个ITEM_ID的最后日期列表。所以下一步将是获得所有这些中最高的,但我卡在那里。

实际上,最终我需要跳过查询中的一些Item_Id,但我想我可以在Select之前添加一个where,像Where(s => s.Item.Id {和这里是一个表达式,检查它是否在我通过的列表中)。

我会很感激的任何提示,

感谢

+0

看到http://stackoverflow.com/questions/1101841/linq-how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-ret – 2012-08-01 23:36:16

回答

2

这是否对你的工作需要什么?

var highestDateID = Storage.OrderByDescending(x => x.Date).Select(x => x.Item_Id).FirstOrDefault(); 
1

为什么不

var lastDateId = Storage 
    .GroupBy(s => s.Item_Id) 
    .Select(grp => new { Id = grp.Key, LastDate = grp.Max(x=>x.Date) }) 
    .OrderBy(o=>o.LastDate).Take(1).Id; 

甚至

var lastDateId = Storage.OrderByDescending(o=>o.LastDate).Take(1).Id; 

,如果你需要一个完整的记录

var record = Storage 
    .Where(w=>w.Id == Storage.OrderByDescending(o=>o.LastDate).Take(1).Id) 
    .First(); 
+0

它不允许我以这种方式访问​​Id,但我猜这是因为我做错了什么。 – mitomed 2012-08-02 09:49:49