简体   繁体   中英

How to sort Odds and Evens in a Dart List

Cant figure out how to do it.

I'm using sort() with compareTo() to sort a list ascending by one criteria, but i need to resort it with a second criteria, keeping odd numbers in the beggining of the list.

widget.tasks.sort((a,b){
          return a.key.compareTo(b.key);
        });

This code above just sorts one of the attributes of the list. A need to sort a second one of integer numbers.

Here is working Example Copy code and run

 List numlist = [1, 2, 3, 4, 5, 6, 7, 9, 10];

  List oddList = [];
  List evenList = [];
  List firstOddThenEven = [];

  for (final i in numlist) {
    if (i.isEven) {
      evenList.add(i);
    } else if (i.isOdd) {
      oddList.add(i);
    }
  }

  firstOddThenEven.addAll(oddList);
  firstOddThenEven.addAll(evenList);
  print(firstOddThenEven);

A more simple approach, which also don't require allocating new List objects, would be:

void main() {
  final numlist = [1, 2, 3, 4, 5, 6, 7, 9, 10];

  numlist.sort((a, b) {
    if (a.isEven && !b.isEven) {
      return 1;
    } else if (b.isEven && !a.isEven) {
      return -1;
    } else {
      return a.compareTo(b);
    }
  });

  print(numlist); // [1, 3, 5, 7, 9, 2, 4, 6, 10]
}

This will also work if the input list are unsorted.

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