2016-04-22 192 views
0
List<DateTime> 

"2015-03-21 13:00:00" 
"2015-05-15 13:00:00" 
"2015-05-24 13:00:00" 
"2015-05-27 13:00:00" 
"2015-06-14 13:00:00" 

我有开始日期2015-05-21 13:00:00)和结束日期2015-06-09 22:00:00获取最近的日期

其实我需要从上述阵列两个日期这是接近或等于开始日期和结束日期。

另外还请注意,离开始日期最近的日期应该等于或在开始日期之前,最接近结束日期的日期应该等于或在结束日期之后。换句话说,给定日期列表,找到包含开始和结束日期的最小日期范围。

在这种情况下,输出将是“2015-05-15 13:00:00”和“2015-06-14 13:00:00”。

如何在c#中实现这一目标?

+4

你试过_anything_解决问题了吗? –

+0

是的,试了很多.. – StackOverflow

+3

所以请显示你的尝试,并解释出了什么问题。 (作为第一个想法,对列表进行排序,执行二进制搜索,并且您将找到匹配的日期或与相邻条目的索引...) –

回答

3
void Main() 
{ 
    var dates = new string[] 
     { 
      "2015-03-21 13:00:00", 
      "2015-05-15 13:00:00", 
      "2015-05-24 13:00:00", 
      "2015-05-27 13:00:00", 
      "2015-06-14 13:00:00" 
     } 
     .Select(x => DateTime.Parse(x)) 
     .ToList(); 

    var start = DateTime.Parse("2015-05-21 13:00:00"); 
    var end = DateTime.Parse("2015-06-09 22:00:00"); 

    Console.WriteLine(dates 
     .Where(x => x <= start) 
     .OrderByDescending(x => x) 
     .FirstOrDefault()); 
    Console.WriteLine(dates 
     .Where(x => x >= end) 
     .OrderBy(x => x) 
     .FirstOrDefault()); 
} 

// the date must be outside of boundary, so this is no longer good... 
//public static DateTime GetClosestDate(IEnumerable<DateTime> source, DateTime date) 
//{ 
// return source 
//  .OrderBy(x => Math.Abs((x.Date - date).TotalSeconds)) 
//  .First(); 
//} 

结果:

GetClosestDate:
2015年5月24日13:00:00
2015年6月14日13:00:00

Where OrderBy [Descendin G] FirstOrDefault:
2015年5月15日13:00:00
2015年6月14日13:00:00

+0

而不是'列表',我们可以使用'List ' – StackOverflow

+0

来实现解决方案这是一个日期时间列表,我只是懒惰而已。 – Xiaoy312

+0

我是否可以在不改变的情况下使用您的代码。 – StackOverflow

2
public DateTime? GetClosest(List<DateTime> dates, DateTime dateToCompare) 
{ 
    DateTime? closestDate = null; 
    int min = int.MaxValue; 

    foreach (DateTime date in dates) 
    { 
     if (Math.Abs(date.Ticks - dateToCompare.Ticks) < min) 
     { 
      min = date.Ticks - dateToCompare.Ticks; 
      closestDate = date; 
     } 
    } 
    return closestDate; 
} 

在谷歌简单搜索涉及this