, List<T>.BinarySearch , "", "" ( ).
:
, , :
class CurrencyHistoricExchangeRateComparer : IComparer<CurrencyHistoricExchangeRate>
{
public int Compare(CurrencyHistoricExchangeRate x, CurrencyHistoricExchangeRate y)
{
// this is just the opposite of the default DateTime comparer
return -x.Date.CompareTo(y.Date);
}
}
, , :
private static int FindIndex(List<CurrencyHistoricExchangeRate> list, DateTime dateTime)
{
var comparer = new CurrencyHistoricExchangeRateComparer();
var idx = list.BinarySearch(
new CurrencyHistoricExchangeRate() { Date = dateTime }, comparer);
// not found? then calculate the bitwise complement to
// get the index of the first larger element
// (this will evaluate to list.Count if there is no such element)
return (idx < 0) ? ~idx : idx;
}
:
var idx = FindIndex(history, someDate);
CurrencyHistoricExchangeRate rate = null;
if (idx < history.Count)
rate = history[idx];
else
throw new InvalidOperationException($"there are no dates smaller than {someDate}");