简体   繁体   English

如何使用 dart 对列表进行排序?

[英]How can i sort list with dart?

I have list like that list = ['1','5','10','25','50','100','250'];我有这样的list = ['1','5','10','25','50','100','250'];

I sort list like that list..sort((a, b) => a.compareTo(b);我像那个列表一样对列表进行排序list..sort((a, b) => a.compareTo(b);

But return但是返回

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

How can i sort like that return我怎样才能像那个回报一样排序

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

You have to first convert String list into int list then you can sort them.您必须先将 String 列表转换为 int 列表,然后才能对它们进行排序。

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.原因是您的数字表示为String对象,因此按字母顺序排序,而不是按值的顺序。 To do that we need to convert each String object into a int object before we compare the values.为此,我们需要在比较值之前将每个String object 转换为int object。

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.前面提到的解决方案有效,但您最终会得到int对象列表,因为它在排序之前首先将List<String>转换为List<int>

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> :如果列表很长,使用其他提到的解决方案会更有效,并且在排序后,将List<int>转换回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]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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