Progress.Collections.IComparer<T> interface

The Progress.Collections.IComparer<T> interface provides a method to support the comparison of objects for equality.

Public Properties

The interface has no public properties.

Public Methods

Compare( ) method (Collections)

Notes

  • The following rules apply when comparing the objects:
    • If the returned value is less than 0 (zero), then the first object sorts before the second object.
    • If the returned value equals 0 (zero), then both objects occupy the same position in the sort order.
    • If the returned value is greater than 0 (zero), then the first object sorts after the second object.
  • For a SortedSet collection, an error is raised if the Compare() method returns the unknown value (?) or raises an exception or error.
  • In order to implement this interface, the comparer user-defined class needs to define the type argument as a specific class type, making it a comparer object for a specific type (or types that inherit that type).

Example

Assume there is a class named Person that defines default ordering for the class:

CLASS Person IMPLEMENTS Progress.Collections.IComparable<Person>: 

  define property Name as char Get. Set.

  method public integer CompareTo(otherObject as Person).

    if this-object = otherObject OR 
      this-object:Name = otherObject:Name then
      return 0.

    else if this-object:Name < otherObject:Name then
      return -1. // current object sorts lower

    // current object sorts higher
    return 1.
  end.
end.

This default ordering can be bypassed by using a custom comparer implementation and defining the ordering rules via the Compare() method. The following example defines a PersonComparer class that implements IComparer<T>, which can be used to override the default ordering defined in the Person class above. Note that the Person class does not need to implement IComparable<T>, but even if it does, the order is still defined by the comparer class below.

CLASS PersonComparer IMPLEMENTS Progress.Collections.IComparer<Person>:
 
  method public integer Compare(person1 as Person, person2 as Person).
  
    // same object, also handles being the unknown value
    if person1 = person2 then
      return 0.

    // object1 sorts lower if it’s the unknown value
    if not valid-object(person1) OR 
       person1:Name < person2:Name then
      return -1.
    else if not valid-object(person2) OR
            person1:Name > person2:Name then
        return 1.

    // sorts the same
    return 0. 
  end.
end.

In order to use the custom comparer, you would instantiate the SortedSet class, passing an instance of the comparer class. For example:

mySet = NEW Progress.Collections.SortedSet<Person>(NEW PersonComparer()).

See also

<T> Generic type reference, Progress.Collections.IComparable<T> interface