How to write linq to get most recent incoming event records
var events = context.Events.........
Events has a property 'DueDate' (Datetime)
I want to select most recent 5 records, how to write su开发者_开发问答ch a query? Thanks
If you are interested in the Events that are closest to day you could do this:
DateTime today = DateTime.Now;
var events = context.Events
.OrderBy(e => Math.Abs((today - e.DueDate).Days))
.Take(5)
.ToList();
This takes the events that are the least number of days away from today (in the past OR future).
If you wanted events that are most recent but only in the future, you could do:
DateTime today = DateTime.Now;
var events = context.Events
.Where(e => e.DueDate >= today)
.OrderBy(e => (e.DueDate - today).Days)
.Take(5)
.ToList();
Edit:
If you use LINQ to Entities DateTime
manipulation is not directly supported, but if you use SQL server something like DateDiff should work (untested you'll have to try out yourself):
DateTime today = DateTime.Now;
var events = context.Events
.Where(e => e.DueDate >= today)
.OrderBy(e => System.Data.Objects.SqlClient.SqlFunctions.DateDiff("d", e.DueDate, today))
.Take(5)
.ToList();
If that doesn't work you can always get your data first, then filter with LINQ to objects, which has the added benefits that you're not tying yourself to SQL Server - but obviously it's not very efficient:
DateTime today = DateTime.Now;
var futureEvents = context.Events
.Where(e => e.DueDate >= today);
.ToList();
var filteredEvent = futureEvents
.OrderBy(e => (e.DueDate - today).Days)
.Take(5)
.ToList();
One way to write it:
var events = context.Events.OrderByDescending(e=>e.DueDate).Take(5);
精彩评论