AMT Help Files

List of Classes Comparer example

On this page an example of a report containing a list of classes with a compare routine is shown.

The class is locally defined to keep the example inside a single object, there are no restrictions to define the globally.

BEGIN_DEFINITIONS
CONST

VAR

    FruitList   : List (FruitClass)
    Fruit_1     : FruitClass
    Fruit_2     : FruitClass
    Fruit_3     : FruitClass
    SearchFruit : FruitClass
    ResultFruit : FruitClass
    FruitIndex  : Numeric 1

TYPE

    // Define the fruit class locally with the 'Implements IComparer' keywords

    FruitClass  : Class Implements IComparer

      PUBLIC
      ProductCode : Numeric 3
      FruitType   : Alpha 20

    END_CLASS

BOOLEANS

END_DEFINITIONS

PUBLIC ROUTINE FruitClass.Compare (A : FruitClass, B : FruitClass: Integer
BEGIN_ROUTINE

// Compare and order the fruits alphabeticly by type.

IF A.FruitType < B.FruitType
   result :-1
ELSEIF A.FruitType > B.FruitType
   result :1
ELSE
   result :0
ENDIF

END_ROUTINE

ROUTINE MAIN
BEGIN_ROUTINE

    // Create 3 FruitClass instances, fill them with data and add them to FruitList.
    FillFruitListClasses ()

    // Sort the list according to the FruitClass compare routine.
    FruitList.Sort()

    // Create an instance with a type of fruit to search inside the fruit list.
    SearchFruit           := FruitClass.CREATE ()
    SearchFruit.FruitType :'Apple'

    // Search the list for an Apple fruit type.
    FruitIndex            := FruitList.IndexOf(SearchFruit)

    // Process the result of the search.
    IF FruitIndex <> 0
        ResultFruit := FruitList[FruitIndex]
        Sme('Searched Fruit code: ',ResultFruit.ProductCode)
    ELSE
        SME('Fruit not found')
        EXIT ALL
    ENDIF


    // Search the list for a second apple.
    FruitIndex := FruitList.IndexOf(SearchFruit,FruitIndex)

    IF FruitIndex <> 0
        ResultFruit := FruitList[FruitIndex]
        Sme('Searched Fruit second code: ',ResultFruit.ProductCode)
    ELSE
        SME('Fruit not found second time around')
    ENDIF

END_ROUTINE

ROUTINE FillFruitListClasses
BEGIN_ROUTINE

    Fruit_1             := FruitClass.CREATE ()
    Fruit_1.ProductCode :055
    Fruit_1.FruitType   :'Banana'
    FruitList.Add (Fruit_1)

    Fruit_2             := FruitClass.CREATE ()
    Fruit_2.ProductCode :275
    Fruit_2.FruitType   :'Apple'
    FruitList.Add (Fruit_2)

    Fruit_3             := FruitClass.CREATE ()
    Fruit_3.ProductCode :867
    Fruit_3.FruitType   :'Apple'
    FruitList.Add (Fruit_3)

END_ROUTINE