#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));
        }
Advertisement

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: