🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators foreach
This page was created by Lars.olofsson on 2021-12-13. Last edited by Wikiadmin on 2026-07-29.

You use foreach in OCL executable actions to perform an action for every item in a collection while keeping the original collection as the result.

Purpose

foreach is an Executable Action Language (EAL) operator. Use it when the expression inside the loop changes state or performs another action, such as deleting an object, clearing a value, or assigning a value.

Unlike collect, foreach does not transform the collection into a collection of expression results. It evaluates the expression once for each item and returns the original collection unchanged.

Syntax

collection->foreach(item | expression)
Part Meaning
collection The collection whose items you want to process.
item A variable that represents the current item during each iteration.
expression An EAL expression to perform for the current item. This expression can delete an object or make an assignment.

Use foreach for side effects

A side effect is a change made while an expression is evaluated. In an executable action, examples include deleting an object or assigning a value.

Use foreach when the action is the purpose of the loop. Do not use it to build a list of values; use collect for that.

Delete every item in an association

The following action deletes every Order associated with the current Customer:

self.Orders->foreach(o | o.delete)
  1. self.Orders is the collection to process.
  2. o represents one Order at a time.
  3. o.delete deletes that order.
  4. The expression returns the original self.Orders collection, rather than a collection of delete-operation results.

Assign a value for every item

For example, if each order has a Status value, you can assign the same value to all orders in the customer's collection:

self.Orders->foreach(o | o.Status := 'Closed')

Here, foreach visits each order and performs the assignment. The result remains the original order collection.

foreach compared with collect

Operator Use it when you need to Result
foreach Perform an EAL action for each item, such as deletion or assignment. The original collection.
collect Calculate a value for each item. A new collection containing the calculated values.

For example, this expression returns customer names and does not change any customer:

Customer.allInstances->collect(c | c.Name)

Notes

  • foreach is an EAL operator. Use it in an executable action context when you need its state-changing behavior.
  • The expression after | is evaluated once per item in the collection.
  • If you need a collection with no duplicate values as input, see Set.

See also