2016-04-22 194 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