Using Array.BinarySearch Generic Method with Custom Objects
Hello,
In this topic I will illustrate how to use BinarySearch Method with custom Objects, and this includes how to sort an array or collection of custom objects.
In fact with Dot Net we can use built-in binary search algorithm to Search an entire one-dimensional sorted Array, also to locate a specific element in the sorted ArrayList. Moreover Searches the entire sorted List<T>… In this topic We will use Array.BinarySearch Generic Method as an example.
This member is overloaded, for example you can use BinarySearch<T>(T[], T) or BinarySearch(Array, Object) .. etc.. Here I will use the first one.
- First we need to create our class:
public class Car { public Car(string ID, string Name) { this.ID = ID; this.Name = Name; } public string ID { get; set; } public string Name { get; set; } }
- second, Implement IComparable<T> generic interface:
We need to implement this Interface because both Sort<T>(T[]) generic method overload and BinarySearch<T>(T[], T) generic method overload use CompareTo method which compares the current object with another object of the same type, this help to sort and search array elements.
public class Car : IComparable<Car> { public Car(string ID, string Name) { this.ID = ID; this.Name = Name; } public string ID { get; set; } public string Name { get; set; } #region IComparable<Car> Members public int CompareTo(Car other) { return this.Name.CompareTo(other.Name); } #endregion }
In this implementation of CompareTo method I suppose that the comparison will be by Name Field, also you can use one or more fields to compare.Whereas the Sort and the Search depend on the code inside CompareTo Method.
- Finally, the following code example demonstrates how to deal with the objects:
static void Main(string[] args) { Car Toyota = new Car("1", "Toyota"); Car Mercedes = new Car("2", "Mercedes"); Car Ford = new Car("3", "Ford"); Car[] carsArr = { Toyota, Mercedes, Ford }; Car searchedCar = new Car("1", "Toyota"); Array.Sort(carsArr); int indexResult = Array.BinarySearch(carsArr, searchedCar); string outputMessage = string.Empty; if (indexResult < 0) { Console.WriteLine("The object to search is not found. The next larger object is at index " + ~indexResult); } else { Console.WriteLine("The object to search is at index " + indexResult); } }
Hope that help.