简体   繁体   English

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

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

I have a list that looks like this我有一个看起来像这样的列表

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}]

and Another list that is aa list of a specific Dart Model but it does contain this matching keyword "handle" call it a "Collection"另一个列表是特定 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')]

They are guaranteed to have the same length and the same "handle" values, but the List<Collection> list needs to follow the "order" key of the List<Map> .它们保证具有相同的长度和相同的“句柄”值,但List<Collection>列表需要遵循List<Map>的“order”键。

Any methods I could use to achieve this?我可以使用任何方法来实现这一目标? Thanks!谢谢!

You have left out some important data types... But if the things you say are guaranteed, and my assumptions of your data types are correct.你遗漏了一些重要的数据类型……但是如果你说的是有保证的,而且我对你的数据类型的假设是正确的。 Then this is one way to make it work:那么这是使其工作的一种方法:

  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);

This DartPad example show the code above given my assumptions.这个DartPad 示例根据我的假设显示了上面的代码。

If it needs to run very fast then there is surely better ways to do it.如果它需要运行得非常快,那么肯定有更好的方法来做到这一点。 One easy thing in my example would be to remove the matching element from myOrder to keep shrinking the search space every time a match has been found.在我的示例中,一件简单的事情是从myOrder中删除匹配元素,以便在每次找到匹配项时不断缩小搜索空间。

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

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