简体   繁体   中英

How can i sort list with dart?

I have list like that list = ['1','5','10','25','50','100','250'];

I sort list like that list..sort((a, b) => a.compareTo(b);

But return

1 - 10 - 100 - 25 - 250 - 5 - 50

How can i sort like that return

1 - 5 - 10 - 25 - 50 - 100 - 250

You have to first convert String list into int list then you can sort them.

List<String> list = ['1', '5', '10', '25', '50', '100', '250'];
List<int> lint = list.map(int.parse).toList();
lint.sort();
print(lint);

The reason is your numbers are represented as String objects and is therefore sorted alphabetically and not in order of values. To do that we need to convert each String object into a int object before we compare the values.

The previous mentioned solution works but you will end up with List of int objects since it first converts the List<String> to List<int> before sorting.

If you don't want that, you can do the following which maintain the original representation of the numbers:

void main() {
  final list = ['1', '5', '10', '25', '50', '100', '250'];
  list.sort((a, b) => int.parse(a).compareTo(int.parse(b)));
  print(list); // [1, 5, 10, 25, 50, 100, 250]
}

If the list are very long, it would be more efficient to use the other mentioned solution and after sorting, convert the List<int> back into List<String> :

void main() {
  List<String> list = ['1', '5', '10', '25', '50', '100', '250'];
  List<int> lint = list.map(int.parse).toList();
  lint.sort();
  list = lint.map((i) => i.toString()).toList();
  print(list); // [1, 5, 10, 25, 50, 100, 250]
}

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