#153 – Returning a Subset of Array Elements Matching a Particular Criteria
November 17, 2010 4 Comments
Because System.Array implements the IEnumerable interface and because LINQ extends IEnumerable, you can use the IEnumerable.Where method on arrays to find a subset of elements that match a particular criteria.
The Where method accepts a delegate to a function that takes a single element of the same type as the array and returns a boolean value, indicating whether a match is found. Where returns an IEnumerable collection, which can be iterated on to get the elements in the subset.
Here’s an example, finding the set of passing scores in a set of scores.
int[] scores = { 89, 98, 72, 100, 68 }; // Count number of passing grades int numPassed = scores.Where((Func<int,bool>)IsPassingGrade).Count();
Here’s the implementation of IsPassingGrade.
static bool IsPassingGrade(int score) { return (score >= 75); }
You can avoid defining a separate function by using a lamba expression.
int numPassed = scores.Where(s => s >= 75).Count();
Similar to Array.FindAll.