#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.
I’m not sure if this was always true, but as of .NET 4.0, the top example could be shortened a bit. These 3 statements all produce the same output:
int numPassed = scores.Where((Func)IsPassingGrade).Count();
int numPassed = scores.Where(IsPassingGrade).Count();
int numPassed = scores.Count(IsPassingGrade);
Similarly, the bottom statement could also be shortened to:
int numPassed = scores.Count(s => s >= 75);
Yes, you’re right–except for your first example, which needs type arguments. You can omit the cast in my example because the types match–i.e. the signature of my method and the Where clause. The intent of my example is to make clear what method signature the Where clause is expecting.
Ugh. My tags got removed. I’ll try this again. That top statement should’ve read:
int numPassed = scores.Where((Func)IsPassingGrade).Count();
Last sentence should say “lambda”, not “lamba”. 🙂