简体   繁体   中英

Sort a list of objects by multiple conditions in Dart

I want to sort a personArray with age and name :

final personArray = [
  _Person(age: 10, name: 'Dean'),
  _Person(age: 20, name: 'Jack'),
  _Person(age: 30, name: 'Ben'),
  _Person(age: 30, name: 'Alice'),
];
personArray.sort((p1, p2) {
  return Comparable.compare(p1.age, p2.age);
});
for (final element in personArray) {
  print(element.name);
}

Console print: Dean Jack Ben Alice.

But what I want is: Dean Jack Alice Ben.

The pseudocode looks like:

personArray.sort((p1, p2) {
  return Comparable.compare(p1.age, p2.age) && Comparable.compare(p1.name, p2.name);
});

Anyway can do it?

Change your compare function

personArray.sort((p1, p2) {
      final compare = Comparable.compare(p1.age, p2.age);
      return compare == 0 ? Comparable.compare(p1.name, p2.name) : compare;
});

you can try this code

  personArray.sort((a, b) {
  return a.name.compareTo(b.name);
  });

it will sort the objects with respect to name.

  personArray.sort((a, b) {
if (a.age != b.age) {
  return a.age - b.age;
}  else {
  return a.name.compareTo(b.name);
}
});

and this will sort it first with age and if both the age are equal then it will sort the objects with respect to name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM