#146 – Using Array.FindAll to Find a Set of Matching Elements in an Array
November 10, 2010 1 Comment
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));
}
Pingback: #153 – Returning a Subset of Array Elements Matching a Particular Criteria « 2,000 Things You Should Know About C#