Is there any way to exit the for each loop before the loop ends

Hi All,


Is there any way to exit the "for each" loop if I met some condition? 

something like break; on c#.net


I try to do something like this, So when the trRelatedEvents.List.Current.IsLinked = true I should be able to exit the loop right away.

But this gives me anerror "Ambiguous paths to End..."


Thanks,

Dan


Solution

Hi Dan,

Try using separate End node:

Solution

Awesome! Yes it's working.

Thanks!!

While this solves the problem, it doesn't actually answer the question?

This won't work if you have a lot of code after the loop.

You need to have the same code in both paths after the loop.

I would suggest set a variable if you have found it in the loop. Found = true. In the iteration of the loop first check this variable. If it's true go back to the start of the loop if it's false continue the iteration.

Now you have only one path after the loop and do not need to double the code after the loop.

Cheers,

Johan

Hello Nathan, 

Why do you think it does not answer the question? Because the solution given is the only way to finish a ForEach looping before it's conclusion. 

Cheers. 

Johan den Ouden wrote:

This won't work if you have a lot of code after the loop.

You need to have the same code in both paths after the loop.

I would suggest set a variable if you have found it in the loop. Found = true. In the iteration of the loop first check this variable. If it's true go back to the start of the loop if it's false continue the iteration.

Now you have only one path after the loop and do not need to double the code after the loop.

Cheers,

Johan

I agree with Johan. Although you could have a number of "wasted" cycles with this approach.

Alternatively, you could extract the foreach logic (as presented by Harlin) into a separate action and then just use that before the "lot of code after the loop".

So the answer to the question is:

NO there is no way to exit a ForEach loop early.


Does anyone know if there is an idea logged for this?
The simple addition of an option "Exit If True" parameter on the ForEach could make a huge difference.

Ignoring the fact that almost every programming language has a way to exit a ForEach loop early, and thus programmers expect to be able to do this, this must be a significant performance hit, and impact on the outsystems shared server hardware requirements.

Hi Nathan,


Yes  there are ideas for this registered there and is a wish for a long time for developers.

Cheers,

Johan