【问题标题】:how to sort list by `enum` in Dart?如何在 Dart 中按“枚举”对列表进行排序?
【发布时间】:2021-05-10 04:31:37
【问题描述】:

如何在 dart 中的 Object 中按 enum 变量对 List<Object> 进行排序?

class Task {
final String name;
final Priority priority;
}

enum Priority {
first,
second,
third
}

List<Task> tasks; // <-- how to sort this list by its [Priority]?

【问题讨论】:

  • 您是否必须使用枚举作为优先级?使用整数优先级会更有意义。
  • @ChristopherMoore 你是对的,但假设我们有一个 List&lt;Restaurant&gt; 并且每个 Restaurant 都有其 Status openbusyclosed 并且我们想要显示打开餐馆起初很忙,然后就关门了,这就是我的情况。

标签: flutter dart


【解决方案1】:

试试这个:

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);
}

假设您的枚举以正确的排序顺序声明。

【讨论】:

  • 您可以在排序回调中使用 a.priority.index,而不需要扩展。 :)
  • 或者,使用 dartx 包,它将 .sortBy 添加到列表中,你可以说tasks.sortBy((e) =&gt; e.priority.index);
  • @RandalSchwartz 哦,当然:D 我试图使优先级可比,但扩展实际上不能做到这一点,不幸的是。并不是说它无论如何都会有很大帮助。只有当 Dart 已经有 sortBy 时才会这样做,所以它看起来很漂亮 tasks.sortBy((t)=&gt;t.priority) 但正如你提到的,你需要一个 lib。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 2011-01-09
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2020-02-10
相关资源
最近更新 更多