http-postballerinax-www-form-urlencodedballerina-httpballerina-swan-lake

How to Select Records from a Ballerina Table Using an Array of IDs?


I'm working on a Ballerina project and I have a table of records called fooTable, which is defined as follows:

type Foo record {|
    readonly int id;
    string name;
|};

table<Foo> key(id) fooTable = table [
    { id: 1, name: "f1" },
    { id: 2, name: "f2" },
    { id: 3, name: "f3" },
    { id: 4, name: "f4" }
];

Now, I need to select a set of Foo records from fooTable based on an array of id values.

int[] ids = [1, 2, 3];
Foo[] selection; // filtering query expression

Solution

  • The easiest way of doing this is using the array:indexOf function to do the fileration.

    Foo[] selection = from Foo foo in fooTable
            where ids.indexOf(foo.id) !is ()
            select foo;