How to efficiently replicate ArrayList.BinarySearch to List <T> .BinarySearch?
I am trying to update an old project using ArrayList collections in List. Everything went pretty smooth except for the ArrayList.BinarySearch conversion. Although List has a corresponding method, ArrayList.BinarySearch has an overload which accepts an arbitrary object , whereas List.BinarySearch requires an object of type T . See example below.
How can I effectively replace this ArrayList function with a list? Or do I have to roll on my own?
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);
}
}
source to share
To use the same method that it uses ArrayList.BinarySearch
, convert List<T>
to an array and call Array.BinarySearch(Array, object)
. Unfortunately, you will need to do the conversion / copy to a new array.
List<SomeType> list;
SomeType value;
// ...
Array.BinarySearch(list.ToArray(), value)
I doubt your approach, although being List<T>
strongly typed will ever contain a type T
. If for some reason you are not sure if the type of this will be listed, check before yourself or follow an extension method to do it for you.
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;
}
}
source to share