ID的BinarySearch对象数组 [英] BinarySearch array of objects by ID
问题描述
美好的一天!
我有一个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类具有此处.>
Good day!
I have a List of ValueObj:
class ValueObj
{
int ID;
float value;
}
How to get binary search objects by id? (List tempValues)
I make ValueComparer class,but dont know am i right?
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; ///???
}
}
I need to sort List by ID. Like that?:
tempValues.Sort(new ValueComparer());
And how to use BinarySearch?
The List class in C# has a BinarySearch method you can use with your Comparable.
Your type:
class ValueObj
{
public int ID{ get; set;}
public float value { get; set;}
}
Your comparison class (do not forget to implement the correct 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;
}
}
Executing a binary search:
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());
There are many more operations you can perform on lists. See the documentation here.
这篇关于ID的BinarySearch对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!