如何在Dart中对字符串列表进行排序? [英] How can I sort a list of strings in 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.
推荐答案
感谢您提出问题!您可以像这样对字符串列表进行排序:
Thanks for the question! You can sort a list of Strings like this:
main() {
var fruits = ['bananas', 'apples', 'oranges'];
fruits.sort();
print(fruits);
}
上面的代码打印:
apples, bananas, oranges
请注意,sort()
不返回值.它对列表进行排序而不创建新列表.如果要在同一行中排序和打印,可以使用方法级联:
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() {
var fruits = ['bananas', 'apples', 'oranges'];
fruits.sort((a, b) => getPrice(a).compareTo(getPrice(b)));
print(fruits);
}
让我们看看这里发生了什么.
Let's see what's going on here.
列表具有 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来表示这样的总排序 如果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.
这篇关于如何在Dart中对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!