How to retrieve a random element of a list?

Hi All, I am looking for a way to retrieve a random name from a list of names. Is this possible? Can I do this by using microflows only?
4 answers

Here is my attempt. I retrieve the amount of records in the database table. Then i multiply this with random() [a random number between 0 and 1] as Ronald pointed out. Then i retrieve that specific object from the database using the RandomOffset and a limit of 1. Becauce Mendix sees this result as a list using the head list operation i can convert the list to an object.


When the list is present in your DB you could retrieve it with a custom range. Set limit to 1 and offset to a random integer that you generate with a custom java action. You should be able to find some Java code that gives you a random number from a range. When a DB retrieve is not possible you could try to loop over the list with a counter. When the counter reaches the random number return the current iterator and stop the loop.


Adjust this


As an extension to Charles Bronzwaer's answer to do this with an in-memory list.

  1. Generate the same random number based on your list length and save this in a variable
  2. then create an iteration number variable
  3. create a variable to store the list item identifier in (make sure you have a unique attribute per list item)
  4. loop over the list until you hit the random created number
  5. Store the unique attribute in the list item identifier variable
  6. Break the loop
  7. Find the list item based on the stored list item identifier variable
  8. Now you have your randomized list item retrieved from the list that was already in memory.
  9. If you are good with Java you could probably make a generic java action to do this in just one microflow action.