简体   繁体   English

是否可以在 C# 中以简单的方式从某个范围内获取数据?

[英]Is it possible to get the data from a range in an easy way in C#?

I have a range of 2 dates given by my business: "we would like to have all data from July and 6 previous months".我的公司给出了 2 个日期范围:“我们希望获得 7 月和前 6 个月的所有数据”。 I create two dates:我创建了两个日期:

_range1.MaxDateTime = new DateTime(today. Year, 7, 31);
_range1.MinDateTime = rangeLastDate.AddMonths(-6).AddDays(1);

Because the system will always perform the calculation on last 6 months.因为系统将始终执行最近 6 个月的计算。 Last date is also always end of month.最后日期也总是月底。 I have no problem to get the last day of the month.我没有问题得到这个月的最后一天。 C# has the feature EndOfMonth() for this. C# 为此具有EndOfMonth()功能。 But when I do so I always get the last day at midnight.但是当我这样做时,我总是在午夜得到最后一天。 when I create the DateTime() myself I also get a date a midnight.当我自己创建DateTime()时,我也会在午夜得到一个日期。

In my code I use Entity Framework with LinQ.在我的代码中,我使用带有 LinQ 的实体框架。 (old EF, not Core yet) (旧的 EF,还不是 Core)

_range1_ShippedQuantities = DbContext.Job_Dtl
    .Where(j=> j.LastShipDate >= _range1.MinDateTime && j.LastShipDate <= _range1.MaxDateTime)

This is not correct because my last datetime is the 31 at midnight and not the first of next month at midnight.这是不正确的,因为我的最后一个日期时间是午夜 31 点,而不是下个月的第一天午夜。 I should do我应该做

_range1_ShippedQuantities = DbContext.Job_Dtl
    .Where(j=> j.LastShipDate.Date >= _range1.MinDateTime.Date && j.LastShipDate.Date <= _range1.MaxDateTime.Date)

Or I can also manipulate the dates do force the time at 23:59:59... what I don't like.或者我也可以操纵日期强制时间为 23:59:59 ......我不喜欢什么。 I still miss 1 second.我仍然错过了 1 秒。 I can add 999 milliseconds but i will still tell you I miss one millisecond.我可以添加 999 毫秒,但我仍然会告诉你我错过了一毫秒。 I can also add one day in a temp variable and use this temp variable in my LinQ query... yes but I have the feeling there is something better.我也可以在一个临时变量中添加一天,并在我的 LinQ 查询中使用这个临时变量......是的,但我觉得有更好的东西。 How do you deal with these ranges?你如何处理这些范围?

But LinQ does not allow this.但是 LinQ 不允许这样做。 LinQ for entities cannot recognize the date.实体的 LinQ 无法识别日期。

As several people have commented on your question, the simplest and most common way to solve this problem is to choose an exclusive end date rather than an inclusive one.正如几个人对您的问题所评论的那样,解决此问题的最简单和最常见的方法是选择一个专有结束日期而不是一个包容性结束日期。

var minDateInclusive = rangeLastDate.AddMonths(-6).AddDays(1);
var maxDateExclusive = rangeLastDate.AddDays(1);
DbContext.Job_Dtl
    .Where(j=> j.LastShipDate >= minDateInclusive 
        && j.LastShipDate < maxDateExclusive);

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

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