繁体   English   中英

根据构造函数参数对飞镖列表进行排序

[英]Sort a dart list based on constructor parameter

我已经定义了这样的课程,

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

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

我有一个喜欢的人的清单,

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM