Skip to main content
 首页 » 编程设计

c#之使用 Array.BinarySearch() 返回第一个值 = 查找值

2024年02月24日24rubylouvre

我正在尝试创建一个“查找”列,该列将返回等于或小于要查找的值的数组值的索引。所以这是我的尝试,似乎工作正常,但我想知道是否有更清洁的方法?

// Sorted 
float[] ranges = new float[] 
  { 
     0.8f, 
     1.1f, 
     2.7f, 
     3.9f, 
     4.5f, 
     5.1f, 
  }; 
 
 
private int GetIndex(float lookupValue) 
{ 
    int position = Array.BinarySearch(ranges, lookupValue); 
    if (position < 0) 
    { 
        // Find the highest available value that does not 
        // exceed the value being looked up. 
        position = ~position - 1; 
    } 
 
    // If position is still negative => all values in array  
    // are greater than lookupValue, return 0 
    return position < 0 ? 0 : position; 
} 

谢谢。

请您参考如下方法:

不,我认为这是一个非常好的方法。

我唯一可能改变的是让它成为数组的扩展方法,而不是引用类变量的私有(private)函数。然后它变得通用/不绑定(bind)到一个类,语法也更清晰:ranges.GetIndex(...)

像这样:

public static class Extensions 
{ 
    public static int GetIndex<T>(this T[] ranges, T lookupValue) 
    { 
        // your code here 
    } 
} 

当然,你必须记住这只适用于排序数组......