简体   繁体   中英

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 such 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();

写它的一种方法:

var events = context.Events.OrderByDescending(e=>e.DueDate).Take(5);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM