#153 – Returning a Subset of Array Elements Matching a Particular Criteria

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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #153 – Returning a Subset of Array Elements Matching a Particular Criteria

  1. 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);

    • Sean says:

      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.

  2. Ugh. My tags got removed. I’ll try this again. That top statement should’ve read:

    int numPassed = scores.Where((Func)IsPassingGrade).Count();

  3. Mason says:

    Last sentence should say “lambda”, not “lamba”. 🙂

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: