【发布时间】:2010-08-11 05:03:50
【问题描述】:
我正在尝试创建一个“查找”列,该列将返回等于或小于正在查找的值的数组值的索引。所以这是我的尝试,似乎效果很好,但我想知道是否有更清洁的方法?
// 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;
}
谢谢。
【问题讨论】:
-
BinarySearch 很快,我认为你所拥有的非常干净。
-
定义 'cleaner'。 代码有效。它很简洁。评论不错。你还在寻找什么?
-
虽然上面的解决方案假设输入数组是排序的......
-
从我的偏好中清除意味着删除冗长的 cmets,但这是一种偏好。我不会碰代码..我认为你有最好的解决方案。
-
也许使用 Array.BinarySearch Method (Array, Object, IComparer) 代替?
标签: c# arrays lookup where-clause binary-search