【问题标题】:How to sort a list by another list如何按另一个列表对列表进行排序
【发布时间】:2021-01-23 21:19:37
【问题描述】:

如何对包含对象的列表进行排序,以便对象的属性与 dart 中的不同列表匹配?

class Example {
  String _id;
  String get id => _id;
}

List examples = [Example(id: 'hey'), Example(id: 'foo'), Example(id: 'baa')]
List ids = ['foo', 'baa', 'hey']

print(examples.sortBy(ids)) ???????


OUTPUT:

  [Example(id: 'foo'), Example(id: 'baa'), Example(id: 'hey')]

【问题讨论】:

  • 您可以将ids 的列表映射到Examples 的列表,而不是排序

标签: list sorting flutter dart


【解决方案1】:

这不是最高效的方式,但它可能是最简单的方式之一。使用基于对象字段在另一个数组中的位置进行排序的排序方法:

final sortedExamples = List.from(examples)
  ..sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));

这种方式稍微复杂一些,但性能更高,因为您只需对每个列表进行一次迭代。它涉及从您的列表中制作一张地图,然后使用它作为事实来源来重建一个排序列表:

final ref = Map.fromIterable(examples, key: (e) => e.id, value: (e) => e);
final sortedExamples = List.from(ids.map((id) => ref[id]));

如果空间有问题,第一种选择更好,如果速度有问题,第二种选择更好。

【讨论】:

  • 太棒了!我每天都从@Abion47 的回答中学到新东西。
猜你喜欢
  • 1970-01-01
  • 2020-03-08
  • 2014-05-28
  • 1970-01-01
  • 2012-02-08
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
相关资源
最近更新 更多