简体   繁体   English

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

[英]how can i use binary search in c# for generic list

I would like to sort my list and then use a binary search to find a name in the list and display it.我想对我的列表进行排序,然后使用二进制搜索在列表中找到一个名称并显示它。

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

The built-in BinarySearch method does not let you pass in a value of a type other than the type of the list.内置的BinarySearch方法不允许您传入列表类型以外的类型的值。 To use the built-in BinarySearch you will need to either define a class that implements IComparer<Animal> that compares by Name , or make Animal implement IComparable<Animal> so that two animals are compared by name by default.要使用内置的BinarySearch ,您需要定义一个 class 来实现按Name进行比较的IComparer<Animal> ,或者让Animal实现IComparable<Animal>以便默认情况下按名称比较两只动物。 Then you Sort() the list and call BinarySearch , passing an Animal instance that has the name you want to search for.然后对列表进行Sort()并调用BinarySearch ,传递一个具有您要搜索的名称的Animal实例。

You'd have to implement your own BinarySearch method to search for an object with a given property value (assuming, of course, that the list is sorted by that same property).您必须实现自己的BinarySearch方法来搜索具有给定属性值的 object(当然,假设该列表按相同的属性排序)。

If you just want to use regular linear search methods to search for an animal with a given name, you can use a straight foreach loop, break ing when the item with that name is found, or use the First() Linq method (which basically does the same thing).如果您只想使用常规线性搜索方法来搜索具有给定名称的动物,您可以使用直接foreach循环,在找到具有该名称的项目时break ,或使用First() Linq 方法(基本上做同样的事情)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM