再会!
我有一个ValueObj列表:
class ValueObj
{
int ID;
float value;
}
如何通过ID获取二进制搜索对象?
(列出tempValues)
我做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?
最佳答案
C#中的List类具有可与Comparable一起使用的BinarySearch方法。
您的类型:
class ValueObj
{
public int ID{ get; set;}
public float value { get; set;}
}
您的比较类(不要忘记实现正确的接口(interface)!):
class ValueObjIDComparer : IComparable<ValueObj>
{
public int Compare(ValueObj x, ValueObj y)
{
if (x == null) return -1;
if (y == null) return 1;
if (x.ID == y.ID) return 0;
return x.ID > y.ID ? 1 : -1;
}
}
执行二进制搜索:
List<ValueObj> myList = new List<ValueObj>();
myList.Add(new ValueObj(){ID=1});
myList.Add(new ValueObj(){ID=2});
// ...
int idToFind = 2;
myList.Sort(new ValueObjIDComparer());
int indexOfItem = myList.BinarySearch(idToFind, new ValueObjIDComparer());
您可以对列表执行更多操作。请参阅文档here。