对元组的二分查找列表查找最接近的值 >=

Tom*_*len 4 c# datetime binary-search

给定一个:

List<Tuple<DateTime, int>>
Run Code Online (Sandbox Code Playgroud)

其中提供的列表按DateTimevalue排序descending

如何使用该.BinarySearch()方法查找大于指定值的值的最小DateTime索引>=

EG,其值为:

[0] = 29th Jan
[1] = 25th Jan
[2] = 20th Jan
[3] = 10th Jan
[4] = 3rd Jan
Run Code Online (Sandbox Code Playgroud)

搜索结果将是:

1st Jan = return 4
5th Jan = return 3
28th Jan = return 0
1st Feb = return something else indicating nothing found (eg -1 or null)
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

由于您的列表的顺序与预期相反BinarySearch,因此您的比较方法需要返回日期比较结果的倒数:

class TupleCompare : IComparer<Tuple<DateTime,int>> {
    public static readonly TupleCompare Instance = new TupleCompare();
    public int Compare(Tuple<DateTime,int> x, Tuple<DateTime,int> y) {
        return -x.Item1.CompareTo(y.Item1); // Note the negative here
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此比较器后,调用BinarySearch,检查其值是否为负,反转其位,然后减 1:

DateTime myDate = ... // desired date
int index = list.BinarySearch(Tuple.Create(myDate, 0), TupleCompare.Instance);
if (index < 0) {
    var res = ~index-1;
} else {
    Console.WriteLine("Exact match at index {0}", index);
}
Run Code Online (Sandbox Code Playgroud)

演示。