簡體   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