简体   繁体   English

如何按另一个列表对列表进行排序

[英]How to sort a list by another list

How can I sort a list with objects so that the properties of the objects match a different list in dart?如何对包含对象的列表进行排序,以便对象的属性与 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')]

This isn't the most performant way, but it's probably one of the simplest.这不是最高效的方法,但它可能是最简单的方法之一。 Use a sorting method that sorts based on the object's field's location in the other array:使用基于对象字段在另一个数组中的位置进行排序的排序方法:

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

This way is slightly more involved but more performant as you only need to iterate over each list once each.这种方式稍微复杂一些,但性能更高,因为您只需要对每个列表进行一次迭代。 It involves making a map out of your list and then using that as the source of truth to rebuild a sorted list:它涉及从您的列表中创建一个 map,然后使用它作为真实来源来重建一个排序列表:

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

The first option is better if space is an issue, the second is better if speed is an issue.如果空间有问题,第一个选项更好,如果速度有问题,第二个选项更好。

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

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