#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers