【问题标题】:List sorting, if integers are same that related strings should be in alphabetical order and the interger values should be ascending order列表排序,如果整数相同,则相关字符串应按字母顺序排列,整数值应按升序排列
【发布时间】:2022-01-24 21:54:56
【问题描述】:

Dart 列表应根据元素对象内的相同整数值按字母顺序排序。如果整数具有相同的值,则这些相关字符串应按 aplhabetical 和升序排列

这是列表。

列表项 = [ People( 10 , 'a' ) , People( 5 , 'c' ), People( 15 , 'b' ), People( 15 , 'a' ), People( 5 , 'k' ), 人(10, 'd') 人(7, 'c')];

预期结果:

列表项 = [ People( 5 , 'c' ) , People( 5 , 'k' ), People( 7 , 'c' ), People( 10 , 'a' ), People( 10 , 'k' ), 人(15, 'a') 人(15, 'd')];

【问题讨论】:

  • People 类是否实现了Comparable?如果是这样,请将其发布,List.sort 文档说:“如果省略比较,则默认 List 实现使用 Comparable.compare。”
  • No 没有实现 Comparable。
  • api.dart.dev/stable/2.15.1/dart-core/Comparable-class.html - 他们说:“具有内在排序的类型使用的接口。compareTo 操作定义了对象的总排序,可用于排序和排序。Comparable接口应该用于类型的自然排序。如果一个类型可以以多种方式排序,并且它们都不是明显的自然排序,那么最好不要使用 Comparable 接口,并提供单独的而是比较器。”
  • 您已经在stackoverflow.com/q/70458967 中提出了这个问题,我将其标记为Sort a list of objects in Flutter (Dart) by property value 的重复项。如果你想问一个好问题,你应该解释为什么这些答案还不够(注意one of the answers(披露:我的)专门解决了如何按多个属性排序)。

标签: flutter sorting dart alphabetical


【解决方案1】:

不需要 Jahidul Islam 建议的双重排序。如果数字相同,您只需要创建一个比较名称的比较方法。所以是这样的:

void main() {
  final items = [
    People(10, 'a'),
    People(5, 'c'),
    People(15, 'b'),
    People(15, 'a'),
    People(5, 'k'),
    People(10, 'd'),
    People(7, 'c'),
  ];

  print(items);
  // [People(10,'a'), People(5,'c'), People(15,'b'), People(15,'a'), People(5,'k'), People(10,'d'), People(7,'c')]

  items.sort((p1, p2) {
    final compareAge = p1.age.compareTo(p2.age);

    if (compareAge != 0) {
      return compareAge;
    } else {
      return p1.name.compareTo(p2.name);
    }
  });

  print(items);
  // [People(5,'c'), People(5,'k'), People(7,'c'), People(10,'a'), People(10,'d'), People(15,'a'), People(15,'b')]
}

class People {
  final int age;
  final String name;

  People(this.age, this.name);

  @override
  String toString() => "People($age,'$name')";
}

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-09-03
    • 2023-03-28
    • 2018-09-15
    相关资源
    最近更新 更多