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 alphabetically 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