[英]How to effectively replicate ArrayList.BinarySearch in List<T>.BinarySearch?
我正在嘗試將舊項目從使用ArrayList集合升級到List。 除了轉換ArrayList.BinarySearch之外,一切都很順利。 雖然List有一個相應的方法,但ArrayList.BinarySearch有一個接受任意對象的重載,而List.BinarySearch需要一個類型為T的對象 。 以下示例。
如何有效地用List替換此ArrayList功能? 或者我必須自己動手?
class Pod {
public DateTime Start { get; set; }
}
class TimeRange: IComparer {
TimeSpan StartsAt { get; set; }
ITimeRangeComparer TimeComparer { get; set; }
public int Compare(object x, object y) {
// there is more to it, but basically compares time ranges
return comparer.Compare((TimeRange) x, (TimeRange) y);
}
}
class Manager {
void DoStuff() {
ArrayList alPods = GetPodsAL();
List<Pod> lstPods = GetPodsLST();
int stopIndex;
TimeRange startPoint = GetStartPoint();
TimeRange stopPoint = GetStopPoint();
// ArrayList works fine
stopIndex = alPods.BinarySearch(stopPoint, startPoint.TimeComparer);
// Fails because the method demands that `stopPoint` be of type Pod
stopIndex = lstPods.BinarySearch(stopPoint, startPoint.TimeComparer);
}
}
要使用ArrayList.BinarySearch
使用的相同方法,請將List<T>
轉換為數組並調用Array.BinarySearch(Array, object)
。 不幸的是,您需要轉換/復制到新陣列。
List<SomeType> list;
SomeType value;
// ...
Array.BinarySearch(list.ToArray(), value)
我確實質疑你的方法,因為List<T>
是強類型的,它只會包含類型T
如果您由於某種原因不確定該類型是否屬於列表中的類型,請事先檢查或制作擴展方法為您執行此操作。
public static class ListExtensionMethods
{
public static int BinarySearch<T>(this List<T> list, object value)
{
if (value is T)
return list.BinarySearch((T)value);
return -1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.