Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a list of objects in a specific order

Let’s say I have a list of Place objects :

class Place {
  String name;
  PlaceType type;

  Place({
    required this.name,
    required this.type,
  });
}

enum PlaceType { museum, cinema, supermarket }

What’s the best way to sort the list by PlaceType in a specific order (let’s say supermarket > cinema > museum) ?

For now I just sort it like below, but I don’t know if I can ask for a specific order there.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

placesList.sort(
    (Place a, Place b) => a.placeType.name.compareTo(b.placeType.name),
  );

>Solution :

You can do

PlaceType.values.indexOf("type")

to find the index of the enum value, then compare the index

 placesList.sort(
    (Place a, Place b) => PlaceType.values.indexOf(b.type).compareTo(PlaceType.values.indexOf(a.type)),
  );

Full code example:

class Place {
  String name;
  PlaceType type;

  Place({
    required this.name,
    required this.type,
  });
}

enum PlaceType { museum, cinema, supermarket }

void main() {
  var placesList = [
    Place(name: 'a', type: PlaceType.cinema),
    Place(name: 'b', type: PlaceType.cinema),
    Place(name: 'c', type: PlaceType.museum),
    Place(name: 'd', type: PlaceType.supermarket),
    Place(name: 'e', type: PlaceType.cinema),
    Place(name: 'f', type: PlaceType.supermarket),
    Place(name: 'g', type: PlaceType.museum),
  ];
  
  var placeTypeValues = PlaceType.values;
  placesList.sort(
    (Place a, Place b) => placeTypeValues.indexOf(b.type).compareTo(placeTypeValues.indexOf(a.type)),
  );

  for (var p in placesList) {
     print('${p.name} - ${p.type}');
  }
}

Output:

d - PlaceType.supermarket
f - PlaceType.supermarket
a - PlaceType.cinema
b - PlaceType.cinema
e - PlaceType.cinema
c - PlaceType.museum
g - PlaceType.museum

If you want to make a custom order from PlaceList enum without changing the enum declaration order, you can create a separate variable like this

List<PlaceType> placeTypeOrder = [PlaceType.cinema, PlaceType.museum, PlaceType.supermarket];

then use placeTypeOrder to find the index

placeTypeValues.indexOf(b.type)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading