如何通过输入一个日期

问题描述:

我想找到它落在输入日期的日期范围内找到日期范围的列表确切日期范围,以下是结构如何通过输入一个日期

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>清单,LINQfor-loop

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

+0

你最好做的'DateTime' –

+0

你的意思是'StartDate'一个'Dictionary'最接近或'EndDate'最接近?你必须更具体。 *'CurrentDate'之后'EndDate'应该*吗? – stybl

+0

开始和结束日期也最接近。 – Jitendra

首先,您需要检查的currentdate是每个范围的开始和结束日期内。对于那些符合这种条件的人,可以计算两个距离之间的“贴近度”。当你找到一个失误(间隙)较小的黄褐色以前,你保存它的指数...瞧

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

谢谢,寻求帮助。 – Jitendra

如果您需要间隔中间是最接近:

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

为d以上勒

  • 首先检查,如果是的currentdate开始和结束中提到的日期
  • 其次选择与起始端结束日期

之间的最小差异我使用的NuGet包称为morelinq这给很好的扩展方法,如MinBy时间:

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