繁体   English   中英

如何根据 Dart 的另一个型号列表对 model 的列表进行重新排序或排序?

[英]How can I reorder or sort list of model based on another List of models with Dart?

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

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 Model 的列表,但它确实包含此匹配关键字“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<Collection>列表需要遵循List<Map>的“order”键。

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

你遗漏了一些重要的数据类型……但是如果你说的是有保证的,而且我对你的数据类型的假设是正确的。 那么这是使其工作的一种方法:

  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 示例根据我的假设显示了上面的代码。

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

暂无
暂无

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

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