You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pharo技术问询:如何从嵌套OrderedCollection提取元素生成单层集合?

解决Pharo嵌套OrderedCollection转单层的问题

你可以用以下两种简洁的方式实现需求:

方法一:使用flatCollect:方法

flatCollect:会自动遍历原集合中的每个子集合,并将子集合的元素平铺到结果集合中:

flattenedCollection := originalCollection flatCollect: [:subCollection | subCollection].

如果需要确保结果严格是OrderedCollection类型(部分场景下flatCollect:可能返回其他Collection子类),可以加上类型转换:

flattenedCollection := (originalCollection flatCollect: [:subCollection | subCollection]) asOrderedCollection.

方法二:使用inject:into:手动合并

通过初始化空集合,逐个添加子集合的所有元素:

flattenedCollection := originalCollection inject: OrderedCollection new into: [:result :subCollection |
    result addAll: subCollection; yourself].

两种方法都能将包含三个子OrderedCollection的外层集合,转换为包含所有String、String、Date元素的单层OrderedCollection,且保留原元素的顺序。

内容的提问来源于stack exchange,提问作者Mansour Faouziel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:35:31