如何通过输入单个日期从日期范围列表中找到确切的日期范围

时间:2017-08-04 10:22:59

标签: c# linq

我想找到输入日期的日期范围,以下是结构

public class Duration
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}


var durations = new List<Duration>();
var duration1 = new Duration()
{
    StartDate = new DateTime(2017, 08, 1),
    EndDate = new DateTime(2017, 08, 10)
};
durations.Add(duration1);
var duration2 = new Duration()
{
    StartDate = new DateTime(2017, 08, 5),
    EndDate = new DateTime(2017, 08, 10)
};
durations.Add(duration2);
var duration3 = new Duration()
{
    StartDate = new DateTime(2017, 08, 5),
    EndDate = new DateTime(2017, 08, 6)
};
durations.Add(duration3);

现在,我想查找与<Durations>LINQ

for-loop列表最接近输入日期的持续时间

currentDate=new DateTime(2017, 08, 7);的预期结果为duration2

3 个答案:

答案 0 :(得分:1)

首先需要检查currentDate是否在每个范围的开始和结束日期之内。对于满足该条件的那些,您计算两个距离的“接近度”。如果您发现前一个时间间隔(间隙)变小,则保存其索引...和voilá

 int lapse = Integer.MaxValue;
 int counter = 0;
 int index = 0;
 foreach (d in durations) {
     if (((d.StartDate <= currentDate) && (d.EndDate >= currentDate))) {
         int newlapse = ((currentDate - d.StartDate).TotalDays + (d.EndDate - currentDate).TotalDays);
         if ((newlapse < lapse)) {
             lapse = newlapse;
             index = counter;
         }
     }    
     counter +=1;     
 }
 return durations(index);

答案 1 :(得分:0)

如果您需要间隔的中间距离最近:

durations.OrderBy((d) => Math.Abs(d.EndDate.Ticks + d.StartDate.Ticks) / 2 - currentDate.Ticks).FirstOrDefault();

如果您需要最接近的间隔开始:

durations.OrderBy((d) => Math.Abs(d.EndDate.Ticks - currentDate.Ticks)).FirstOrDefault();

答案 2 :(得分:0)

As D le mentioned above

  • First check if currentDate is within the start and end dates
  • Second select the duration with the minimal difference between start end end date

I used a nuget package called morelinq which gives nice extensions methods like MinBy:

var result = (from d in durations
              where (d.StartDate <= currentDate && d.EndDate >= currentDate)
              select d).MinBy(d => d.EndDate - d.StartDate);