简体   繁体   中英

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"

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> .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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