[英]Latest date in Linq to sql
Say I have a table named Storage with records this kind 假设我有一个名为Storage的表,其中包含此类记录
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
I would like to get the Item_Id with the latest Date associated to it (in this case it would be then "4") using linq to sql. 我想使用linq to sql获取Item_Id,其中包含与之关联的最新日期(在本例中,它将是“4”)。
I'm using this expression 我正在使用这个表达式
var lastDate= Storage
.GroupBy(s => s.Item_Id)
.Select(grp => new {
grp.Key,
LastDate = grp.OrderByDescending(
x => x.Date).First()
}).ToList();
and I'm getting a list with the latest date for each item_Id. 我得到一个列表,其中包含每个item_Id的最新日期。 So the next step would be to get the highest of all of them, but I'm stuck there.
因此,下一步将是获得所有这些中最高的,但我被困在那里。
Actually, eventually I'd need to skip some of the Item_Id's in the query but I guess I'll be able to add a where before the Select, something like Where(s => s.Item.Id {and here an expression that checks if it's inside the list I pass). 实际上,最终我需要跳过查询中的一些Item_Id,但我想我能够在Select之前添加一个where,类似于Where(s => s.Item.Id {和这里的一个表达式检查它是否在我通过的列表中。
I'd appreciate any hint, 我很欣赏任何提示,
Thanks 谢谢
这是否适合您的需求?
var highestDateID = Storage.OrderByDescending(x => x.Date).Select(x => x.Item_Id).FirstOrDefault();
Why not 为什么不
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;
or even 甚至
var lastDateId = Storage.OrderByDescending(o=>o.LastDate).Take(1).Id;
and if you need a full record 如果你需要一个完整的记录
var record = Storage
.Where(w=>w.Id == Storage.OrderByDescending(o=>o.LastDate).Take(1).Id)
.First();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.