我正在尝试创建一个“查找”列,该列将返回等于或小于正在查找的值的数组值的索引。所以这是我的尝试,它似乎工作正常,但我想知道是否有更清洁的方法?
// 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;
}
谢谢。