美好的一天!
我有一个 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/