我需要一些巫师。
我有一张桌子
Start End PersonID
-----------------------------------------------------
10/07/2017 00:00:00 18/07/2017 00:00:00 1
27/07/2017 00:00:00 27/07/2017 00:00:00 1
28/07/2017 00:00:00 28/07/2017 00:00:00 1
29/07/2017 00:00:00 29/07/2017 00:00:00 1
30/07/2017 00:00:00 30/07/2017 00:00:00 1
如果我搜索
Date Start = 11/07/2017
Date End = 12/07/2017
使用此查询:
DateTime start = new DateTime(2017,07,11,0,0,0,0,0);
DateTime end = start.AddDays(1);
DateTime[] days = new DateTime[end.Subtract(start).Days];
for (int i = 0; i < end.Subtract(start).Days; i++)
{
var d = start.AddDays(i);
days[i] = d;
}
IQueryable block = tmOpen1.Calendar.Where(x => days.All(y => y >= x.start && y <= x.end)).Select(x => new { ID = x.PersonID });`
我得到第1轮(2017年7月10日 - 2017年7月18日)的正面结果
但是,如果我将其应用于剩余的行,例如过滤
Date Start = 28/07/2017
Date End = 29/07/2017
然后显然这会失败。我怎样才能使搜索的这一面起作用。
E.g。任
我希望这里有一位天才可以提供帮助。
答案 0 :(得分:1)
似乎所有你真正需要的是这样的:
DateTime start = new DateTime(2017,07,11,0,0,0,0,0);
DateTime end = start.AddDays(1);
var results = tmOpen1.Calendar
.Where(c => start <= c.end && end >= c.start)
.Select(x => new { ID = x.PersonID });
答案 1 :(得分:1)
如果您的间隔在表格的开始日期和结束日期之间的某个位置开始或结束,那么它意味着重叠并且您应该包含在结果中。
tmOpen1.Calendar.Where(x => (startDate >= x.start && startDate <= x.end) || (endDate >= x.start && endDate <= x.end)).Select(x => new { ID = x.PersonID });
所以间隔10.07 - 27.07会给你前2行,对吧?
或者该区间应该完全包含在表格中的两个日期之间吗?
答案 2 :(得分:0)
时间范围无效的简化:
DateTime start = new DateTime(2017, 07, 11, 0, 0, 0, 0, 0);
DateTime end = start.AddDays(1);
var results = tmOpen1.Calendar.
.Where( c => ! ( c.Start > end || c.End < start) )
.Select(x => new { ID = x.PersonID } );
对于DateTime start = new DateTime(2017, 07, 11, 0, 0, 0, 0, 0);
结果是:
TEST 1: 11/07/2017 00:00:00
Start:10/07/2017 00:00:00 End:18/07/2017 00:00:00 ID:1
对于DateTime start = new DateTime(2017, 07, 28, 0, 0, 0, 0, 0);
结果是:
TEST 2: 28/07/2017 00:00:00
Start:28/07/2017 00:00:00 End:28/07/2017 00:00:00 ID:1
Start:29/07/2017 00:00:00 End:29/07/2017 00:00:00 ID:1
答案 3 :(得分:0)
了解您的问题时,您想知道Date Start
或Date End
何时在某个日期范围内。
您可以查看Date Start
是否在日期范围内,或Date End
是否在日期范围内
示例:
List<DateRange> dates = new List<DateRange>();
dates.Add(new DateRange()
{
StartDate = new DateTime(2017, 07, 10),
EndDate = new DateTime(2017, 07, 18)
});
dates.Add(new DateRange()
{
StartDate = new DateTime(2017, 07, 28),
EndDate = new DateTime(2017, 07, 28)
});
DateRange search1 = new DateRange()
{
StartDate = new DateTime(2017, 07, 11),
EndDate = new DateTime(2017, 07, 12)
};
DateRange search2 = new DateRange()
{
StartDate = new DateTime(2017, 07, 28),
EndDate = new DateTime(2017, 07, 29)
};
var result1 = dates.Where(x => search1.StartDate >= x.StartDate && search1.StartDate <= x.EndDate ||
search1.EndDate <= x.StartDate && search1.EndDate >= x.EndDate);
var result2 = dates.Where(x => search2.StartDate >= x.StartDate && search2.StartDate <= x.EndDate ||
search2.EndDate <= x.StartDate && search2.EndDate >= x.EndDate);