比较LINQ过去的日期 [英] Compare past dates in LINQ
问题描述
我必须写找到一个项目在过去90天内出现在数据库中的次数一个LINQ声明。这很简单,但他们希望看到在1-30天,31-60天,61-90和天计算的数据。
I have to write a LINQ statement that finds the number of times an item appears in a database over the past 90 days. That's easy but they are wanting to see the data in terms of 1-30 days, 31-60 days, and 61-90 days.
我目前在做什么正在创建具有四组数据的模型,得到的所有唯一的SKU列表,然后发现他们有多少次出现在数据库中。
What I'm currently doing is creating a model that has the four sets of data, getting a list of all the unique SKU's, and then finding how many times they appear in the data base.
我的问题是日期范围。我创造新的DateTime对象和新增排除天他们,我试图用它来比较范围。我想不出怎么说这样的事情:
My problem is the date ranges. I'm create new DateTime objects and adding NEGATIVE days to them and I'm trying to use that to compare ranges. I can't figure out how to say something like this:
编辑日期(30日)和(-60天)
Edited date is between (-30 days) and (-60 days).
我不能使用SP这一点。必须有一个更简单的方法。也许使用的时间跨度,看它是否落在跨度?我不确定。我很少使用日期合作
I can't use a SP for this. There has to be an easier way. Maybe using a time span and seeing if it falls in that span? I'm not sure. I rarely work with dates.
推荐答案
是这样的:
DateTime today = DateTime.Today;
DateTime minusThirty = today.AddDays(-30);
DateTime minusSixty = today.AddDays(-60);
// Normally I wouldn't use a query expression for just a single where clause,
// but I assume you want more...
var query = from item in db.Table
where item.Date >= minusSixty && item.Date < minusThirty
select item;
您的可能的希望< =
和>
而不是 - 你应该工作是为自己。但是,您几乎可以肯定想的有一个的必然是包容和的有一个的必然是排他性的,并利用这些一致 - 这样没有项目将在多个斗结束。
You may want <=
and >
instead - you should work that out for yourself. However, you almost certainly want one bound to be inclusive and one bound to be exclusive, and use those consistently - that way no item will end up in more than one bucket.
这篇关于比较LINQ过去的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!