Using Predicates over foreach in Arrays

We generally use foreach blocks to iterate through Arrays n Lists in order to operate on them which not only makes our code long n confusing but also makes us compromise on performance. The solution to this lies in Predicates...


Arrays are integral part of our programming languages. They are the data structures that contain a number of variables of the same datatype. Array class has various methods for sorting, searching and manipulating.

When it comes to fetching a matching value from an array or lists, we generally use foreach blocks to iterate through them which not only makes our code long n confusing but also makes us compromise on performance. The System.Array and System.Collections.Generic.List classes of the .NET Framework 2.0 each provide a number of methods that can aid us in getting rid of foreach blocks.

The methods in System.Array class such as Find, FindAll, and FindLast, let us avoid writing code to loop through every element of an array or list to find the one or more items we're looking for. This gives us the ability to "walk" an entire data structure, determining whether each item meets a set of criteria, without having to write the boilerplate code to loop through each row manually.

This is made possible by the use of PREDICATES. Predicate is simply the address of a procedure to call that, in effect, says yea or nay on each item in the collection, you can easily change the search criteria at run time.

Lets examine this through the following simple example:

using System;

 

public class City

{

 

    public static void Main()

    {

        // Create an array of string objects.

        string[] names = new string[3];

        names[0] = "London";

        names[1] = "Paris";

        names[2] = "Zurich";

        // To find the first city name structure which starts with alphabet "P", pass the array

        //  and a delegate that represents the ProcessCity method to the Shared

        //  Find method of the Array class.

        string[] city;

        city = Array.Find(names, StartsWithP);

        // Note that you do not need to create the delegate

        // explicitly, or to specify the type parameter of the

        // generic method, because the C# compiler has enough

        // context to determine that information for you.

        // Display the first city found.

        Console.WriteLine("City Match Found: {0}", city);

    }

    // This method implements the test condition for the Find

    // method.

    public static bool StartsWithP(string item)

    {

        return item.StartsWith("P", StringComparison.InvariantCultureIgnoreCase);

    }

}

/* This code example produces the following output:

City Match Found: Paris

 */ 

The benefit of using Predicates is that they are more expressive, require less code, promote reuse, and are faster than other alternatives. Using a Predicate turns out to have better performance than a similar foreach operation.

For a thorough knowledge of benefits of Predicates over foreach there is this wonderful article:

http://msmvps.com/blogs/jon.skeet/archive/2006/01/20/foreachperf.aspx