我想通过Dart中的对象中的枚举变量对对象列表进行排序?例如:
class Task { final String name; final Priority priority; } enum Priority { first, second, third } List<Task> tasks; // <-- how to sort this list by its [Priority]?
字符串
bkkx9g8r1#
试试这个:
class Task { final String name; final Priority priority; Task(this.name, this.priority); @override toString() => "Task($name, $priority)"; } enum Priority { first, second, third } extension on Priority { int compareTo(Priority other) =>this.index.compareTo(other.index); } List<Task> tasks = [ Task('zort', Priority.second), Task('foo', Priority.first), Task('bar', Priority.third), ]; main() { tasks.sort((a, b) => a.priority.compareTo(b.priority)); print(tasks); }
字符串它假设您的枚举以正确的排序顺序声明。
inb24sb22#
通常,您会使用官方的package:collection/collection.dart包。然后你可以这样做:
package:collection/collection.dart
import 'package:collection/collection.dart'; // modify existing list tasks.sortBy<num>((e) => e.priority.index); // create sorted copy final sortedTasks = tasks.sortedBy<num>((e) => e.priority.index);
<num>
int
Comparable<int>
cgfeq70w3#
Dart 2.17和更高版本使它更容易,仅在新的增强Enums中的用户成员,例如:
enum Priority { first(1), second(2), third(3); const Priority(this.val); final int val; } tasks.sort((a, b) => a.priority.val.compareTo(b.priority.val));
3条答案
按热度按时间bkkx9g8r1#
试试这个:
字符串
它假设您的枚举以正确的排序顺序声明。
inb24sb22#
通常,您会使用官方的
package:collection/collection.dart
包。然后你可以这样做:
字符串
<num>
泛型,因为int
不实现Comparable<int>
。更多详情请看这里:https://github.com/dart-lang/sdk/issues/43763的cgfeq70w3#
Dart 2.17和更高版本使它更容易,仅在新的增强Enums中的用户成员,例如:
字符串