Friday, September 12, 2008

Predicates: List.Find() method

When it comes to searching an element in a list in C#, it seems easier to write a for loop, and iterate over the elements until the desired element is found. In other words, a linear or sequential search.

As an example, a LocationVO has two members: Code and Description.
public class LocationVO
{
    private string code;
 
    /// <summary>
    /// Gets or sets the code.
    /// </summary>
    /// <value>The code.</value>
    public string Code
    {
        get { return code; }
        set { code = value; }
    }
 
    private string description;
 
    /// <summary>
    /// Gets or sets the description.
    /// </summary>
    /// <value>The description.</value>
    public string Description
    {
        get { return description; }
        set { description = value; }
    }
}

The list declaration would be as follows:
List<LocationVO> locations = new List<LocationVO>();

And the linear search would be:
/// <summary>
/// Finds the business location.
/// </summary>
/// <param name="code">The code.</param>
/// <returns></returns>
public LocationVO FindLocation(string code)
{
    if (locations != null)
    {
        for (int i = 0; i < locations.Count; i++)
        {
            if (locations[i].Code = code)
                return locations[i];
        }
    }
    return null;
}

Predicates
An more elegant way is to use the List.Find() method. This method uses a predicate that defines the search criteria. If an element has to be searched by using another criteria (e.g. using the description property rather than the code one), it would be better to write another predicate rather than duplicating the linear search algorithm in the source code.
/// <summary>
/// Finds the location using predicate.
/// </summary>
/// <param name="code">The code.</param>
/// <returns></returns>
public LocationVO FindLocationUsingPredicate(string code)
{
    LocationVO vo = locations.Find(delegate(LocationVO curr)
    {
        return curr.Code == code;
    });
 
    return vo;
}

The List.FindAll() method is yet another interesting method that returns all instances matching the search criteria.

No comments: