[英]How can I retrieve the biggest date and time from the column using Linq to entity?
I have datetime column named DateMeasure
in sql table. 我在SQL表中有一个名为
DateMeasure
datetime列。
I use entity framework 6 in my .net project. 我在.net项目中使用实体框架6。
Here is example of my table: 这是我的桌子的例子:
Id | NumberP | TrackNumber | DateMeasure
28092|15240000|1.0.7.1782|2009040004731|2008-01-20 13:10:22.000
28094|61615000|1.0.7.1782|2009040007696|2010-05-20 13:11:38.000
28095|95317000|1.0.7.1782|2009040007695|2011-08-20 13:10:18.000
28101|15240000|1.0.7.1782|2009040004740|2015-11-20 14:10:22.000
28103|61615000|1.0.7.1782|2009040007690|2015-11-20 14:11:38.000
28104|95317000|1.0.7.1782|2009040007710|2009-02-20 14:10:18.000
The row that I want to get from table with help of Linq to entity: 我想借助Linq从表中获取到实体的行:
28103|61615000|1.0.7.1782|2009040007690|2015-11-20 14:11:38.000
How can I retrieve the biggest(latest) date and time from the column using Linq to entity? 如何使用Linq到实体从列中检索最大(最新) 日期和时间 ?
You can get the max date using Max
extension: 您可以使用
Max
扩展名获取最长日期:
var maxDate = context.Table.Max(m => m.DateMeasure);
Then, you can use FirstOrDefault
to get that entity: 然后,您可以使用
FirstOrDefault
来获取该实体:
var model = context.Table.FirstOrDefault(m => m.DateMeasure == maxDate);
Actually, you can do it in just one query: 实际上,您只需要执行一个查询即可:
var model = context.Table.FirstOrDefault(m => m.DateMeasure == context.Table.Max(x => x.DateMeasure));
You can use the OrderBy
methods of a IQuery object in Linq to sort by the DateMeasure
column and fetch the first entry. 您可以在Linq中使用IQuery对象的
OrderBy
方法对DateMeasure
列进行排序并获取第一个条目。
(from s in context.Table
orderby s.DateMeasure descending).First()
Or with: 或搭配:
context.Table
.OrderByDescending(s => s.DateMeasure)
.First();
The OrderByDescending
method will sort the query in descending order, you can also use OrderBy
to sort by ascending order. OrderByDescending
方法将按降序对查询进行排序,您也可以使用OrderBy
按升序进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.