I have datetime column named DateMeasure
in sql table.
I use entity framework 6 in my .net project.
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:
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?
You can get the max date using Max
extension:
var maxDate = context.Table.Max(m => m.DateMeasure);
Then, you can use FirstOrDefault
to get that entity:
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.
(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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.