简体   繁体   中英

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. 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. Then you Sort() the list and call BinarySearch , passing an Animal instance that has the name you want to search for.

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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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