How can you sort a dictionary

I have a dictionary with a number of keys including “FirstName”, “LastName”, “Company” etc. I want to give my users the option to be able to sort the data stored in the dictionary by each of these fields in both A2Z and Z2A order. Can anyone suggest a good way to do this?

The .keys method returns an array you can easily sort. Then loop through the Dictionary in either way using the array.

Dictionaries can’t be sorted. They are actually sorted internally in buckets by the hashes of values.

But you can sort them yourself on output.

If I’m understanding what you need here, you could store an array of dictionaries and then build a secondary array containing for example the last name from each dictionary. Then call sortwith to sort the dictionaries in the order of last name. To reverse, you would use a loop to invert the array.

  1. create a proper class - don’t use a dictionary for this
  2. then you can store these in an array and sort it however you want