Use "If" to loop or "ForEach" when i might be leaving the loop earlier

I retrieve data from an entity and use the output list to make some logic. 

Let's say if entity.IsRegistered is true i don't need to check the other results and i can just leave.

Should i still use the forEach loop and let it finish the loop or do the loop by myself with the if and control the index and leave the loop when i need?

Hope it is understandable. Thank you.

You could use ListIndexOf to retrieve the position of the first IsRegistered = true; and then set the Maximum Itterations for the ForEach.

Hi! 

That would depend on the expected length of list, if the list is normally very long I would build the loop myself, if it is normally short, the ForEach is good.  

Hope have helped

Graça

Matthias Preuter wrote:

You could use ListIndexOf to retrieve the position of the first IsRegistered = true; and then set the Maximum Itterations for the ForEach.

Thank you for the awnser Matthias. Wouldn't this decrease performance since it is kinda like doing 2 ForEach?(I'm assuming thats what ListIndexOf does behind the curtain)


Solution

No ListIndexOf is much faster, please look at this article

List we forget

(And personally, I don't like exiting a ForEach with a If)

Solution

If you put the entire ForEach inside a separate server action, you can use an if inside the ForEach and then point to an end node to exit the ForEach loop prematurely. (that is technically the only way to do it)

Remains the point if "For Each" is appropriate when you are not doing it for each record. But in my opinion, using this type of "search" should only be done on small lists. On larger lists, preferrably you want the results filtered before you go looping over them. (this is not always possible off course)