简体   繁体   English

如何编写linq以获取最新的传入事件记录

[英]How to write linq to get most recent incoming event records

var events = context.Events......... var events = context.Events .........

Events has a property 'DueDate' (Datetime) 活动有'DueDate'属性(日期时间)

I want to select most recent 5 records, how to write such a query? 我想选择最近的5条记录,如何编写这样的查询? 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): 如果您使用LINQ to Entities DateTime操作不是直接支持,但如果您使用SQL Server, DateDiff之类的东西应该可以工作(未经测试,您将不得不自己尝试):

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: 如果这不起作用,您可以始终先获取数据,然后使用LINQ过滤到对象,这样可以增加您不会将自己绑定到SQL Server的好处 - 但显然效率不高:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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