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

标签 c# arrays lookup where-clause binary-search

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

// 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
    }
}

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

关于c# - 使用 Array.BinarySearch() 返回第一个值 <= 查找值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3452862/

相关文章:

java - 如何在Java中跳过第一个int逐行读取文件到数组?

mongodb - 为什么 $lookup 中的 "as"会替换整个集合?

c - 如何将指针存储到二维数组中?

php - 如何使用 array_flip 在 PHP 中翻转多维数组

XSLT 总和来自另一个文件的查找值

c# - 在 Silverlight 5 中使用动态 JSON - 不工作

c# - 覆盖回车键,但保留 wpf 数据网格中其他键的默认行为

c# - 包括 MySQL Connector/ODBC 5.1 到 C# 应用程序

c# - 在 SQL Server 数据库中保存字体的最佳方法