Simplicity is the ultimate sophistication, and with over 40 methods in 4D v16 R6 to manage collections, things are getting much easier for you as a developer. Not only is your code clean and more readable, but its also written in record time!
The query and indices methods, as in a traditional 4D query, are used to manipulate and retrieve items in a collection. They work exactly the same, the only difference is in the returned result: query returns a collection containing all of the objects matching the search condition defined by the query argument, while indices returns a collection of indexes.
You can mix two types of operators to query your collection. The following code samples show you what’s possible and how to proceed.
How to write a query?
There are two possible ways to write a query:
- query as a string:
$c:=New collection(New object("Id";128;"City";"Paris";"Weather";1))
- or query with placeholder. With this way, you can easily create dynamic queries, and 4D converts your variables for you:
The previous examples were just to show the syntax, but obviously to find something in a four-element collection, a loop would have been enough. The real strength of the query method is when you need to find something in an object or a collection containing a large quantity of data. The query method is a very efficient way to access data.
The example below shows how easy it is now to find the number of operations an administrator has performed today:
// Save the current log file to JSON and put it in a collection
LOG FILE TO JSON("c:\\ExportLogs")
$txt:=Document to text("c:\\ExportLogs\\JournalExport.json")
// Count how many operations have been done by "Administrator"
Comparison operators are used to compare one expression to another. The result of a comparison can be TRUE or FALSE. The comparison operators are:
Logical operators are used to test the validity of a condition. Like comparison operators, they return TRUE or FALSE. The logical operators are:
$col:=$c.query("Id>50 AND (Weather>10 OR Weather<0)")
$col2:=$c.indices("Id>50 AND (Weather>10 OR Weather<0)")