鑒于:
List<DateTime> descOrderedDates;
還有一個日期時間:
DateTime fromDate;
我可以輕松計算日期大于fromDate以下的專案數:
var count = descOrderedDates.Count(c=> c > fromDate);
但是,我正在努力將其實作為BinarySearch:
var ix = descOrderedDates.BinarySearch(fromDate, new CompareDates());
private class CompareDates : IComparer<DateTime>
{
public int Compare(DateTime compareDate, DateTime fromDate)
{
if (fromDate > compareDate) return 1;
return 0;
}
}
這1在fromDate小于串列中最小日期的測驗用例中不斷回傳。我正在努力回過頭來IComparer,誰能告訴我我做錯了什么?
uj5u.com熱心網友回復:
你的比較器在 的情況下回傳 1 fromDate > compareDate,但在相反的情況下它也應該回傳 -1,只有當它們相等時才回傳 0。您是否需要自定義比較器?我相信對于日期,默認比較會正常作業。
uj5u.com熱心網友回復:
您應該回傳負值、正值或 0 in Compare,具體取決于引數是大于、小于還是等于彼此,如檔案所述。(因此您根本不回傳負值的實作是不正確的。)
你可以做到這一點的明確寫出的三種情況,并與比較的日期<和>,但DateTime有CompareTo方法(因為它實作了IComparable),所以你可以使用,而不是:
public int Compare(DateTime date1, DateTime date2)
=> date2.CompareTo(date1);
請注意,當我們呼叫 時CompareTo,兩個日期的順序是顛倒的,以實作Comparer我們正在實作的 的降序。
如果要查找日期小于 的串列的第一個索引fromDate,還需要對 進行一些檢查ix:
int firstIndexLessThanFromDate;
if (ix < 0) {
// applying bitwise not gives you where the element should be inserted
// i.e. the index of the next smallest element
firstIndexLessThanFromDate = ~ix;
} else {
firstIndexLessThanFromDate = ix 1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338583.html
