Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IList

Getting the index of an item in a sorted IList

0.00/5 (No votes)
8 Dec 2011CPOL 5.6K  
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)