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?
first of all you should make your class like this. your fields were not public and you can not access them, also public fields are not good so you should change them to property
class ValueObj
{
public int ID { get; set; }
public float value { get; set; };
}
and your comparer like this
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;
}
}
then you have a list like
var tempValues = new List<ValueObj>();
//many items are added here
you should always sort your list before performing a binary serach
//this does not modify the tempValues and generate a new sorted list
var sortedList = tempValues.OrderBy(x => x.ID).ToList();
or you can sort tempValues
directly
//tempValues is modified in this method and order of items get changed
tempValues.Sort(new ValueComparer<ValueObj>());
now you want to find index of specific ValueObj
var index = sortedList.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());
or if you have used second method of sorting
var index = tempValues.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With