【问题标题】:DART - reorder or sort list of model based on another List of modelsDART - 根据另一个模型列表重新排序或排序模型列表
【发布时间】:2022-11-17 05:54:11
【问题描述】:

我有一个看起来像这样的列表

var myOrder = [{handle: cpap-machines, order: 1}, {handle: cpap-masks, order: 2}, {handle: cpap-mask-parts, order: 3}, {handle: cpap-supplies, order: 4}, {handle: cpap-cleaning, order: 5}, {handle: cpap-batteries, order: 6}, {handle: oxygen-therapy, order: 7}, {handle: bundles, order: 8}]

和另一个列表,它是一个特定 Dart 模型的列表,但它确实包含这个匹配的关键字“handle”,称之为“Collection”

List<Collection> = [Collection(handle: 'cpap-machines'), Collection(handle: 'bundles'), Collection(handle: 'cpap-mask-parts'), Collection(handle: 'cpap-cleaning'), Collection(handle: 'cpap-supplies'), Collection(handle: 'cpap-batteries'), Collection(handle: 'cpap-masks'), Collection(handle: 'oxygen-therapy')]

它们保证具有相同的长度和相同的“句柄”值,但List&lt;Collection&gt; 列表需要跟在List&lt;Map&gt; 的“顺序”键之后。

我可以使用任何方法来实现这一目标?谢谢!

【问题讨论】:

  • myOrder 中,参数cpap-machines 是字符串还是您定义的其他对象?

标签: flutter algorithm dart


【解决方案1】:

你已经离开了一些重要的数据类型......但是如果你说的是有保证的,并且我对你的数据类型的假设是正确的。那么这是使其工作的一种方法:

  final sorted = List<Collection?>.filled(collection.length, null);

  for (var c in collection) {
    sorted[(myOrder.firstWhere((e) => (e['handle'] as String) == c.handle)['order'] as int) - 1] = c;
  }
  print(sorted);

DartPad example 根据我的假设显示了上面的代码。

如果它需要运行得非常快,那么肯定有更好的方法来做到这一点。在我的示例中,一件简单的事情是从 myOrder 中删除匹配元素,以便在每次找到匹配项时不断缩小搜索空间。

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2015-02-27
    • 2021-05-21
    • 2013-04-17
    • 2021-05-25
    • 2023-04-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多