65.9K
CodeProject is changing. Read more.
Home

Getting the index of an item in a sorted IList

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Dec 8, 2011

CPOL
viewsIcon

5663

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 TreeNodes in a TreeNodeCollection, yesterday I used it...

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 TreeNodes 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.