#146 – Using Array.FindAll to Find a Set of Matching Elements in an Array

Instead of using Array.Find to find the first matching element in an array, you can use Array.FindAll to find all elements that match a particular set of criteria.  If no elements match, FindAll returns null.

Here we search for the Bronte sisters in an array of people:

            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("Bronte", "Ernie");

            // Finds Emily and Charlotte but not Ernie
            Person[] brontes = Array.FindAll(folks, IsABronteSister);

Here is the function that looks for a match:

        static bool IsABronteSister(Person p)
        {
            string[] firstNames = { "Emily", "Charlotte", "Anne" };

            return (p.LastName == "Bronte") && (firstNames.Contains(p.FirstName));
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #146 – Using Array.FindAll to Find a Set of Matching Elements in an Array

  1. Pingback: #153 – Returning a Subset of Array Elements Matching a Particular Criteria « 2,000 Things You Should Know About C#

Leave a comment