Skip to content

Comparison Based Filtering

ahzf edited this page Feb 23, 2011 · 3 revisions

More complicated filters can be created than what was presented above. These filters usually check objects to determine whether to emit them or not. There is an interface called IComparisonFilterPipe<S, T>. Implementations of this interface consume objects of type S. If a check of that object passes (returns true), then the S object is emitted, else it is filtered. The IComparisonFilterPipe has the following signature:

public interface IComparisonFilterPipe<S, T> : IFilterPipe<S>
    where S : IComparable
    where T : IComparable
{
    Boolean CompareObjects(T myLeftObject, T myRightObject);
}

public enum ComparisonFilter
{
    EQUAL, NOT_EQUAL, GREATER_THAN, LESS_THAN, GREATER_THAN_EQUAL, LESS_THAN_EQUAL
}

The important method is CompareObjects(). This method returns true if the left hand object is EQUAL, NOT_EQUAL, etc. to the right hand object.

Next, there is an abstract class called AbstractComparisonFilterPipe<S, T> that implements IComparisonFilterPipe<S, T>. More specifically, it provides a standard implementation of IComparisonFilterPipe.CompareObjects(). For most situations, this method is sufficient. However, if not, simply override the method with an implementation that meets the requirements of the designed pipe.

public Boolean CompareObjects(T myLeftObject, T myRightObject)
{

    switch (_Filter)
    {

        case ComparisonFilter.EQUAL:
            if (null == myLeftObject)
                return myRightObject == null;
            return myLeftObject.Equals(myRightObject);

        case ComparisonFilter.NOT_EQUAL:
            if (null == myLeftObject)
                return myRightObject != null;
            return !myLeftObject.Equals(myRightObject);

        case ComparisonFilter.GREATER_THAN:
            if (null == myLeftObject || myRightObject == null)
                return true;
            return myLeftObject.CompareTo(myRightObject) == 1;

        case ComparisonFilter.LESS_THAN:
            if (null == myLeftObject || myRightObject == null)
                return true;
            return myLeftObject.CompareTo(myRightObject) == -1;

        case ComparisonFilter.GREATER_THAN_EQUAL:
            if (null == myLeftObject || myRightObject == null)
                return true;
            return myLeftObject.CompareTo(myRightObject) >= 0;

        case ComparisonFilter.LESS_THAN_EQUAL:
            if (null == myLeftObject || myRightObject == null)
                return true;
            return myLeftObject.CompareTo(myRightObject) <= 0;

        default:
           throw new Exception("Invalid state as no valid filter had been provided!");
         
    }

}

Note: In many situations, such as ObjectFilterPipe, the right hand object to allow or disallow is stored in the pipe and compared with each object passed through it.

Filtering Pipes home Sideeffect Pipes