【问题标题】:How to use the dart sort method (with sample code)dart排序方法的使用方法(附示例代码)
【发布时间】:2021-09-23 19:06:42
【问题描述】:

仓库在下面

https://github.com/kanari3/flutter_sort_sample

我按startedDate对项目进行排序,然后尝试在startedDate范围内按startedDatetime排序。

class Item {
  //required
  int id;
  DateTime createdAt;
  DateTime startedDate;
  DateTime endedDate;
  //optional
  DateTime startedDatetime;
  DateTime endedDatetime;

在编写 if 表达式时,我注意到 return 0 是乱序的。

How to use the dart sort method (with sample code)

第一个排序结果

result
id,  startedDate,              startedDateTime,          endedDatetime
2,   2020-11-06 00:00:00.000,  null                   ,  null
1,   2020-11-06 00:00:00.000,  2020-11-06 08:00:00.000,  2020-11-06 17:00:00.000
3,   2020-11-06 00:00:00.000,  null                   ,  null
4,   2020-11-07 00:00:00.000,  2020-11-07 08:00:00.000,  2020-11-07 17:00:00.000
5,   2020-11-07 00:00:00.000,  null                   ,  null
6,   2020-11-07 00:00:00.000,  null                   ,  null
7,   2020-11-08 00:00:00.000,  2020-11-08 08:00:00.000,  2020-11-08 17:00:00.000

在这里,startedDate 已正确排序,但仍不是理想的结果。

我的理解。 我认为 sort 方法如果 item1 和 item2 大于等于 1 则交换 item1 和 item2,如果小于 0 则不执行任何操作。

但结果如下(第二次排序结果)

result
id,  startedDate,              startedDateTime,          endedDatetime
12,  2020-11-12 00:00:00.000,  null                   ,  null
1,   2020-11-06 00:00:00.000,  2020-11-06 08:00:00.000,  2020-11-06 17:00:00.000
3,   2020-11-06 00:00:00.000,  null                   ,  null
.
.

为什么会这样? 另外,我该如何解决这个问题?

测试如下

https://github.com/kanari3/flutter_sort_sample/blob/master/test/sort_test.dart

【问题讨论】:

    标签: flutter sorting dart


    【解决方案1】:

    看起来你需要一个两级比较:首先比较startedDate,并返回差异如果非零,否则(即,如果startedDate-s相等)比较startedDateTime。整个排序将在一次调用中完成。

    顺便说一句,检查sort() 文档,可能它不能保证“相等”的项目保持它们的相对顺序......

    【讨论】:

    • 我已经查看了以下文档api.dart.dev/be/137051/dart-core/List/sort.html >> 整个排序将在一次调用中完成
    • 你看过了吗?所以你应该已经看到了这部分:一个比较器可以比较对象是否相等(返回零),即使它们是不同的对象。排序函数不保证是稳定的,因此比较为相等的不同对象可能在结果中以任何顺序出现这正是你得到的:具有相同startedDateTime 的对象按该值分组在一起,但不保留之前由startedDate 确定的顺序。同样适用于使用比较器 return 0; 进行排序 - 它表示所有项目都是平等的,尽管它们不保持先前的顺序。
    • 谢谢。终于明白文档的意思了!
    【解决方案2】:

    嗯,很难在一个进程中编写分组排序逻辑。

    【讨论】:

      【解决方案3】:

      我找到了一个不错的图书馆!

      https://pub.dev/packages/sorted

      我解决了如下问题。

      https://github.com/kanari3/flutter_sort_sample/blob/master/lib/main.dart#L32-L44

      items.sorted([
        SortedComparable<Item, DateTime>(
          (item) => item.startedDate,
        ),
        SortedComparable<Item, DateTime>(
          (item) => item.startedDatetime, invert: true,
        ),
        SortedComparable<Item, DateTime>(
          (item) => item.endedDatetime,
        ),
      ]);
      

      太棒了!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-16
        • 2019-11-22
        • 2013-05-13
        • 2014-12-07
        • 2021-02-24
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        相关资源
        最近更新 更多