BinarySearch array of objects by ID

Good afternoon!

I have a list of ValueObj:

class ValueObj
{
   int ID;
   float value;
}

How to get binary search objects by id? (TempValues ​​list)

I am making a ValueComparer class but don't 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 the list by ID. Like this?:

tempValues.Sort (new ValueComparer ());

And how to use BinarySearch?

+4
source share
3 answers

The List class in C # has a BinarySearch method that you can use with your comparable one.

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;
    }
 }

Performing 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()); 

. . .

+1

, . , , ,

    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

serach

 //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>());
+2

ID, :

return x.ID > y.ID;
0

All Articles