如何在 Dart 中对字符串列表进行排序? [英] How can I sort a list of strings in Dart?

查看:54
本文介绍了如何在 Dart 中对字符串列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 API 文档中看到 List 上有一个 sort() 方法,但我不清楚它需要什么参数.当前需要进行非常简单的直接 alpha 比较.

I see in the API docs there is a sort() method on List, but I'm not clear what it needs for a parameter. The current need is for a very simple straight up alpha comparison.

推荐答案

1.快速解决方案

感谢提问!您可以像这样对 String 列表进行排序:

main() {
  final List<String> fruits = <String>['bananas', 'apples', 'oranges'];
  fruits.sort();
  print(fruits);
}

上面的代码打印:

[apples, bananas, oranges]

2.稍微高级的用法

请注意 sort() 不返回值.它在不创建新列表的情况下对列表进行排序.如果要排序和打印在同一行,可以使用方法级联:

2. Slightly more advanced usage

Notice that sort() does not return a value. It sorts the list without creating a new list. If you want to sort and print in the same line, you can use method cascades:

print(fruits..sort());

为了更多控制,您可以定义自己的比较逻辑.以下是根据价格对水果进行排序的示例.

For more control, you can define your own comparison logic. Here is an example of sorting the fruits based on price.

main() {
  final List<String> fruits = <String>['bananas', 'apples', 'oranges'];
  fruits.sort((a, b) => getPrice(a).compareTo(getPrice(b)));
  print(fruits);
}

让我们看看这里发生了什么.

Let's see what's going on here.

List 有一个 sort 方法,它有一个 可选 参数:一个 比较器.比较器是 typedef 或函数别名.在这种情况下,它是一个函数的别名,如下所示:

A List has a sort method, which has one optional parameter: a Comparator. A Comparator is a typedef or function alias. In this case, it's an alias for a function that looks like:

int Comparator(T a, T b)

来自文档:

Comparator 函数通过在 a 小于 b 时返回负整数、如果 a 等于 b 返回零、如果 a 大于 b 返回正整数来表示这样的总排序.

A Comparator function represents such a total ordering by returning a negative integer if a is smaller than b, zero if a is equal to b, and a positive integer if a is greater than b.

3.如何使用自定义对象列表进行操作

此外,如果您创建一个由自定义对象组成的列表,您可以将 Comparable 添加为 mixin 或继承(extendscode>) 然后覆盖 compareTo 方法,以便为您的自定义对象列表重新创建 sort() 的标准行为.有关详细信息,请查看其他相关的 StackOverflow 答案.

3. How to do it with a list of custom objects

Additionally, if you create a list composed of custom objects, you could add the Comparable<T> as a mixin or as inheritance (extends) and then override the compareTo method, in order to recreate the standard behavior of sort() for your list of custom objects. For more info, do check out this other, related StackOverflow answer.

这篇关于如何在 Dart 中对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆