c# - 按 ID 的 BinarySearch 对象数组

标签 c# .net list compare binary-search

美好的一天!

我有一个 ValueObj 列表:

class ValueObj
{
   int ID;
   float value;
}

如何通过id获取二分查找对象? (列出温度值)

我创建了 ValueComparer 类,但不知道我是否正确?

class ValueComparer<ValueObj>
{
   public int Compare(ValueObjx, ValueObjy)
   {
       if (x == y) return 0;
       if (x == null) return -1;
       if (y == null) return 1;

       return -1; ///???
   }
}

我需要按 ID 对列表进行排序。像那样?:

tempValues.Sort(new ValueComparer());

以及如何使用 BinarySearch?

最佳答案

首先你应该把你的课变成这样。 您的字段不是公开的,您无法访问它们, 公共(public)领域也不好,所以你应该把它们改成属性(property)

    class ValueObj
    {      
        public int ID { get; set; }
        public float value { get; set; };
    }

你的比较器是这样的

class ValueComparer : IComparable<ValueObj>
{
  public int Compare(ValueObj x, ValueObj y)
  {
      if (ReferenceEquals(x, y)) return 0;
      if (x == null) return -1;
      if (y == null) return 1;

      return x.ID == y.ID ? 0 :
               x.ID > y.ID ? 1 : -1;
  }
}

然后你有一个像这样的列表

var tempValues = new List<ValueObj>();
//many items are added here

在执行二进制搜索之前,您应该始终对列表进行排序

 //this does not modify the tempValues and generate a new sorted list
 var sortedList = tempValues.OrderBy(x => x.ID).ToList();

或者您可以直接对 tempValues 进行排序

//tempValues is modified in this method and order of items get changed
tempValues.Sort(new ValueComparer<ValueObj>());

现在你想找到特定ValueObj的索引

var index = sortedList.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());

或者如果你使用了第二种排序方法

var index = tempValues.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());

关于c# - 按 ID 的 BinarySearch 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26786135/

相关文章:

c# - 在 WinRT 中将视频上传到 Youtube

.net - 如何使用 ADO.NET 和 Oracle 在一次调用中运行多个不同的 `insert` 语句?

c# - 不支持的重载用于查询运算符 'Distinct'

c# - 在 Visual Studio 外部运行时从 WPF 窗口中删除图标

string - 如何在没有迭代的情况下在 Dart 中将 list<String> 转换为 String?

c# - 异步 Web 服务调用是否始终调用 AsyncCallback?

c# - 如何从数据行数组中删除数据行?

c# - 如何使用 linq 验证用户名/密码?

python - 迭代从 .txt 文件转换的列表时遇到问题

c - 打印列表时省略最后一个逗号