#145 – Using Array.Find to Search an Unsorted Array
November 9, 2010 2 Comments
You can use Array.BinarySearch to search a sorted array taking O(log n) time, but if you have an unsorted array, you can search it in O(n) time using the Array.Find method.
The Find method takes an array to search and a function that knows how to look for a match. This matching function accepts a single element of the array and returns true or false, depending on whether a match is found.
Find returns a reference to the object in the array, or null if a match is not found.
static void Main(string[] args) { Person[] folks = new Person[4]; folks[0] = new Person("Bronte", "Emily"); folks[1] = new Person("Bronte", "Charlotte"); folks[2] = new Person("Tennyson", "Alfred"); folks[3] = new Person("Mailer", "Norman"); Person thereHeIs = (Person)Array.Find(folks, FindNorman); folks[3].LastName = "Mailman"; } static bool FindNorman(Person p) { return ((p.FirstName == "Norman") && (p.LastName == "Mailer")); }
Pingback: #151 – Determining Whether an Array Contains a Specific Element « 2,000 Things You Should Know About C#
I believe if Find/FindAll fail, they return null for reference types only (their default value)… for value types (int, double, float), they return their default values (0, 0.0, etc)…