以相同的方式对两个列表排序



我需要对DateTime列表从最早到最晚进行排序。

List<DateTime> list = [2021-01-15 12:26:40.709246, 2021-02-25 13:26:40.709246, 2021-02-20 19:26:40.709246];
datetimeList.sort();

我有另一个字符串列表。

List<String> list = ["one", "two", "three"];

stringList的索引必须与datetimeList的索引匹配。所以1的索引;必须始终与索引2021-01-15 12:26:40.709246相同,以此类推。

如果我对列表单独排序,则DateTime按DateTime排序,string按字母顺序排序。这样,String就不再与它的初始日期一致了。

我如何排序一个列表(datetimeList)与其他列表(stringList)排序完全相同的方式?

最简单的解决方案是创建一个结构/类来组合这两个变量,这样您就不必担心保持数组中的对象对齐。您需要做的最后一件事是按日期对数组中的新对象进行排序。对于这一点,我无法帮助你,因为我缺少关于Dart的知识。

你也可以使用splitemap https://api.dart.dev/stable/2.8.4/dart-collection/SplayTreeMap-class.html.

spplaytreemap确保它的键是有序的。您可以使用您的datetime作为键,并使用其他列表的内容作为值。


main() {
final SplayTreeMap<DateTime, String> map =
new SplayTreeMap<DateTime, String>();
map[DateTime.parse("2021-01-15 12:26:40.709246")] = "one";
map[DateTime.parse("2021-02-25 13:26:40.709246")] = "three";
map[DateTime.parse("2021-02-20 19:26:40.709246")] = "two";
for (final DateTime key in map.keys) {
print("$key : ${map[key]}");
}
}

我推荐这里给出的更简单的建议。

为了完整起见,我将提供另一种方法:通过对索引列表排序来计算排列:

List<int> sortedPermutation<T>(List<T> elements, int compare(T a, T b)) =>
[for (var i = 0; i < elements.length; i++) i]
..sort((i, j) => compare(elements[i], elements[j]));

然后你可以重新排序现有的列表来匹配:

List<T> reorder<T>(List<T> elements, List<int> permutation) =>
[for (var i = 0; i < permutation.length; i++) elements[permutation[i]]];

如果你这样做:

var sorted = reorder(original, sortedPermutation(original, compare));

它应该给你一个排序列表。

它比就地排序效率低,因为你创建了一个新的列表,但是之后你可以对多个列表应用同样的重新排序。

快速有效的方法。

void main() {
final l1 = [3, 1, 2];
final l2 = ['three', 'one', 'two'];
final l3 = ['drei', 'ein', 'zwei'];
print(l1);
print(l2);
print(l3);
myCompare(int x, int y) => x.compareTo(y);
l1.sortLists([l2, l3], myCompare);
print('============');
print(l1);
print(l2);
print(l3);
}
extension SortListByList<E> on List<E> {
sortLists(Iterable<List> lists, int Function(E, E) compare) {
for (final list in lists) {
if (list.length != length) {
throw StateError('The length of lists must be equal');
}
}
final rules = <int>[];
sort((x, y) {
final rule = compare(x, y);
rules.add(rule);
return rule;
});
for (final list in lists) {
var rule = 0;
list.sort((x, y) => rules[rule++]);
}
}
}

输出:

[3, 1, 2]
[three, one, two]
[drei, ein, zwei]
============
[1, 2, 3]
[one, two, three]
[ein, zwei, drei]

最新更新