I wasn't going to publish this version, but I just used it a second time, so maybe someone else will need it too. This is very much like the second version above except that it uses a non-generic
IList
. Today, I used this to find and insert
TreeNode
s in a
TreeNodeCollection
, yesterday I used it with a
ComboBox.Items
.
public static bool TryGetIndex<T,U>
(
this System.Collections.IList List
,
T Sought
,
Comparison<T,U> Comparer
,
out int Index
)
{
bool result = false ;
Index = 0 ;
int lo = 0 ;
int hi = List.Count - 1 ;
while ( !result && ( lo <= hi ) )
{
Index = lo + ( hi - lo ) / 2 ;
int diff = Comparer ( Sought , (U) List [ Index ] ) ;
if ( diff == 0 )
{
result = true ;
}
else if ( diff < 0 )
{
hi = Index - 1 ;
}
else
{
lo = ++Index ;
}
}
return ( result ) ;
}
Note that this is not as type-safe as when using the generic version. This hasn't caused me any trouble (yet) and you can add some protection if you encounter any problems.