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

56 views Asked by At

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
2

There are 2 answers

0
Lakshan Weerasinghe On BEST ANSWER

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;
0
Mindula On

We can also use query join as follows

int[] ids = [1, 2, 3];
Foo[] selection = from Foo foo in fooTable
     join int id in ids on foo.id equals id
     select foo;