Search code examples
sortingocl

How to SortBy two parameters in OCL?


I need to sort the collection of Persons by two parameters, by Surnames and after by Names. How can I do something like this in OCL?


Solution

  • The sortedBy function sorts elements using a the criteria expressed in its body and a < relationship between each gathered result.

    In your case, assuming that you have a surname attribute, the following statement will sort the collection c using the < operator on each surname gathered (so a < on strings):

    c->sortedBy(p | p.surname)
    

    An idea could be to compute a unique string using the surname and the name concatenated toghether. Thus, if you have:

    • George Smith
    • Garry Smith
    • George Smath

    The comparison would be done between "Smith_George", "Smith_Garry" and "Smath_George" and would be ordered, following the lexicographical order, to:

    1. George Smath (Smath_George)
    2. Garry Smith (Smith_Garry)
    3. George Smith (smith_George)

    Finally, the OCL request would be (assuming surname and name as existing attributes):

    c->sortedBy(p | p.surname + '_' + p.name)
    

    This little trick does the job, but it is not "exactly" a two parameters comparison for sortedBy.