65.9K
CodeProject 正在变化。 阅读更多。
Home

在排序后的 IList 中获取项目索引

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2011年12月8日

CPOL
viewsIcon

5810

我原本不打算发布这个版本,但最近又用了一次,也许其他人也会需要。这与上面的第二个版本非常相似,只是它使用了一个非泛型的 IList。今天,我用它来查找和插入 TreeNodeCollection 中的 TreeNode,昨天我用它...

我原本不打算发布这个版本,但最近又用了一次,也许其他人也会需要。这与上面的第二个版本非常相似,只是它使用了一个非泛型的 IList。今天,我用它来查找和插入 TreeNodes 到 TreeNodeCollection 中,昨天我用它与 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 ) ;
}
请注意,这不如使用泛型版本那样类型安全。到目前为止,这没有给我带来任何问题(尚未),如果遇到任何问题,您可以添加一些保护措施。
© . All rights reserved.