Get last element from list

Hello, After I retrieve a list from the database, I want to get the last element in that list. I saw that I can get the first element and made some custom action.   Need your help please.
4 answers

If you know the sorting of the list, you could also retrieve the first item in your XPath retrieve action (instead of all) and apply sorting in a way that the last object will be the first object in your retrieve action. In that way, you don't need to look for the item in the list, you retrieve the correct object right away. GL



This is not standard in Mendix.

Without custom action you could retrieve the list first and count the objects in the list. Do a a custom retrieve next with :amount: 1 Offset : TotalCountOfObjectsInList - 1

To use the object, you can then use the ‘head’ operation.


Have a look at Appstore app ListUtils. It does not have a straightforward ‘getLast’ but maybe the ‘Sort’ and ‘getFirst’ will get you there.


I solved this problem in a different way.

  1. I have an AutoNumber attribute to make sure that the latest added item always has the largest number. (I needed it anyway to display my table with the latest item on top)
  2. Then, in the Retrieve Object activity, I sort the AutoNumber attribute in descending order, then the first item becomes the last item.


I think this is kind of “cheating”, but it works if adding an AutoNumber attribute is not a problem.
I hope there is a better way to solve this.