arrays - 根据构造函数参数对 Dart 列表进行排序

标签 arrays algorithm sorting flutter dart

我定义了这样一个类,

class Person {
  final int id,
  final String name,
  final String email,
  final int age,

  Person({
    this.id,
    this.name,
    this.email,
    this.age});
}

我有一个 Person 的列表,

List<Person> persons;

现在,我需要根据它的构造函数参数(如 id 或 age)对这个列表进行排序。我怎样才能做到这一点?

最佳答案

你应该用 sort 做到这一点方法。

这是一个简单的例子,按人名对列表进行排序:

class Person {
  final int id;
  final String name;
  final String email;
  final int age;

  Person({
    this.id,
    this.name,
    this.email,
    this.age});

  @override
  String toString() {
    return "Person $name";
  }
}

void main () {
  List<Person> people = new List();
  people
    ..add(Person(name: "B"))
    ..add(Person(name: "A"))
    ..add(Person(name: "D"))
    ..add(Person(name: "C"));

  people.sort((p1, p2) => p1.name.compareTo(p2.name));
  print(people);
}

输出:

[Person A, Person B, Person C, Person D]

关于arrays - 根据构造函数参数对 Dart 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57226530/

相关文章:

c++ - n 作为参数传递给函数后为 0,这里似乎有什么问题?

javascript - 避免 Math.random() 函数上的某些组合

javascript - 如何在 Apps 脚本中展平和转置数组

java - 在数组中查找其值总和等于给定总和的索引对

php - 引用 - 这个错误在 PHP 中意味着什么?

python - 关于 Python 内置的 sort() 方法

java - 判断一个列表是否是另一个具有正确顺序的列表的有序子集的函数 c# 或 java

java - 如何查找文件中的子字符串是否已存在于 hashmap 中?

c# - 同时排序/从列表中删除数据

python - Pandas 基于两对列进行排序