如何在Dart中通过对象中的枚举变量对对象列表进行排序?

brccelvz  于 2023-07-31  发布在  其他
关注(0)|答案(3)|浏览(121)

我想通过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]?

字符串

bkkx9g8r

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

字符串
它假设您的枚举以正确的排序顺序声明。

inb24sb2

inb24sb22#

通常,您会使用官方的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);

字符串

cgfeq70w

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

字符串

相关问题