Foreach

The iteration statement ForEach executes a statement or statement block for each element in a collection.

Description

In the AI-Framework, the Foreach loops through any of the following collections.

When using collections, it is often needed to loop through the collection. This is where we use the Foreach statement.

At any point within the Foreach statement block, you can break out of the loop using the Break . You can step to the next iteration in the loop using the Continue .

C# example

A simple C# example of using for each shows the Fibonacci sequence.

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibNumbers)
{
    Console.WriteLine($"Element: {element}");
}

All we need is a collection and a foreach statement to loop through that collection. In this example, the foreach loops through the integer list, that consists of 8 numbers. While looping through the collection, the statement (block) displays the numbers all at a new line.

 

AI-Framework example

In the following code example, Foreach loops through a view.

InvoicesView.Foreach(selectedInvoice => new Body
{
   selectedInvoice.Print()
})

All we need is a collection and a foreach statement to loop through that collection. This example shows a Foreach loop in the AI-Framework using a DataView of Invoices. Here all invoices in the DataView need to be printed.

Another example is a more direct approach to the database.

var articles = Db.Article.Select<ArticleEntity>(AutoLoad.Off)
   .Where(a => a.ProductGroupKey.IsEqualTo(SomeProductGroupKey));

return new Body
{
   articles.Load(),
   articles.Foreach(a => new Body
   {
      a.Code.Assign(ProductGroupView.Current.ProductCode)
   }),
articles.Save()
};

In line 1 and 2 the variable articles is declared as all records of the database file Article (connected with the ArticleEntity), where the Foreign Key ProductGroupKey equals SomeProductGroepKey.

The body is part of a Method. First it loads the articles in line 6. Then, in line 7, Foreach loops through articles and performs the statements within the body of lines 8-10.

> See also the similar While  statement.

 

Lambda expressions in the AI-Framework:

A lambda expression separates the paramater list (on the left) from the body. The body can either be an expression, or a statement block.
It looks like this:

a => expression, like a.ProductGroupKey.IsEqualTo(SomeProductGroupKey)
or
a => { one or more statements }, like new Body { ... }

The parameter on the left can have any name. In the code example above it is called a, since it is about articles.