如何在c#中使用二进制搜索来搜索通用列表?

问题描述 投票:0回答:1

我想对我的列表进行排序,然后使用二进制搜索找到列表中的名字并显示出来。

public abstract class animal {
  protected int age
  protected string name
  public print() {
    console.writeline({
      age
    } + {
     name
    });
  }
  animal() {}~animal() {}
}

public class pets {
  private List<animal> list = new List<animal>();

  public void search(string m) {
    int index = list.BinarySearch(m);
    if (index == 0)
      list[index].print();
  }
}
c# sorting binary-search
1个回答
0
投票

内置的 BinarySearch 方法不允许你传入一个非列表类型的值。要使用内置的 BinarySearch 你将需要定义一个实现了 IComparer<Animal> 相比之下 Name或使 Animal 实施 IComparable<Animal> 所以,两个动物的名字默认是比较的。然后你 Sort() 名单和电话 BinarySearch,通过 Animal 实例,其中有你想搜索的名字。

你必须实现你自己的 BinarySearch 方法来搜索具有给定属性值的对象(当然,假设列表是按该属性排序的)。

如果你只是想使用常规的线性搜索方法来搜索一个具有给定名称的动物,你可以使用直接的 foreach 循环。break命名的项目,或者使用 First() Linq方法(基本是一样的)。

© www.soinside.com 2019 - 2024. All rights reserved.