BinarySearch ID对象数组

时间:2014-11-06 17:54:47

标签: c# .net list compare binary-search

美好的一天!

我有一个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排序List。像那样?:

tempValues.Sort(new ValueComparer());

如何使用BinarySearch?

3 个答案:

答案 0 :(得分:2)

首先,你应该让你的班级像这样。 你的字段不公开,你无法访问它们, 公共领域也不好,所以你应该把它们改成属性

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

答案 1 :(得分:1)

C#中的List类有一个BinarySearch方法,可以与Comparable一起使用。

您的类型:

class ValueObj
{
    public int ID{ get; set;}
    public float value { get; set;}
}

您的比较课程(不要忘记实现正确的界面!):

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

答案 2 :(得分:0)

如果您想按ID排序,您只需比较比较方法中的ID:

return x.ID > y.ID;