如何使用ID数组从Ballerina的fooTable中筛选Foo记录?
Ballerina中基于ID数组筛选记录表记录的实现方法
现有如下Ballerina代码定义的记录类型和记录表:
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" } ];
需要根据给定的ID数组ids = [1, 2, 3],筛选出对应的Foo记录数组,以下是两种可行的实现方式:
方法一:使用查询表达式
这是Ballerina中处理集合筛选的简洁写法,通过from...where...select语法完成筛选:
int[] ids = [1, 2, 3]; Foo[] selection = from Foo f in fooTable where ids.includes(f.id) select f;
方法二:利用主键高效查找
由于id是记录表的主键,使用get()方法可以直接通过ID快速定位记录,这种方式在数据量较大时性能更优:
int[] ids = [1, 2, 3]; Foo[] selection = []; foreach int id in ids { Foo? f = fooTable.get(id); if f is Foo { selection.push(f); } }
两种方式都能得到目标结果:[{id: 1, name: "f1"}, {id: 2, name: "f2"}, {id: 3, name: "f3"}]。如果记录表数据量较大,推荐使用第二种方法,因为主键查找的时间复杂度为O(1),整体效率更高。
内容的提问来源于stack exchange,提问作者Lakshan Weerasinghe
相关产品推荐
相关产品推荐

