c# - How to effectively replicate ArrayList.BinarySearch in List<T>.BinarySearch? -
i trying upgrade old project using arraylist collections list. went pretty smooth, except converting arraylist.binarysearch. while list has corresponding method, arraylist.binarysearch has overload accepts arbitrary object while list.binarysearch demands object of type t. illustration below.
how can replace arraylist functionality list? or have roll 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 more it, compares time ranges homecoming 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 method demands `stoppoint` of type pod stopindex = lstpods.binarysearch(stoppoint, startpoint.timecomparer); } }
to utilize same method arraylist.binarysearch
uses, convert list<t>
array , phone call array.binarysearch(array, object)
. unfortunately need conversion/copy new array.
list<sometype> list; sometype value; // ... array.binarysearch(list.toarray(), value)
i question approach though, beingness list<t>
strongly-typed, ever contain type t
. if you're unsure reason whether type of in list check before-hand or create extension method you.
public static class listextensionmethods { public static int binarysearch<t>(this list<t> list, object value) { if (value t) homecoming list.binarysearch((t)value); homecoming -1; } }
c# generics arraylist binary-search
No comments:
Post a Comment