我有一个列表,我需要按其子项列表中的最高时间戳对其进行排序。
所以流程应该是这样的:
DateTime added
MainItem
对象class MainItem {
final String title;
final List<SubItem> subItem;
MainItem(this.title, this.subItem);
}
class SubItem {
final DateTime added;
SubItem(this.added);
}
我有工作代码,不确定执行多种排序是否是最有效的方法?
final items = <MainItem>[...]
items.sort((a, b) {
a.subItem.sort((a, b) => b.added.compareTo(a.added));
b.subItem.sort((a, b) => b.added.compareTo(a.added));
return b.subItem.last.added.compareTo(a.subItem.last.added);
});
答案 0 :(得分:0)
import 'package:queries/collections.dart';
void main() {
var items = col(_getMainItems());
var query1 = items.orderBy((mi) =>
col(mi.subItem).orderBy((si) => si.added).firstOrDefault()?.added);
var list1 = query1.toList();
print('Ascending');
for (var element in list1) {
print(element);
}
var query2 = items.orderByDescending((mi) =>
col(mi.subItem).orderBy((si) => si.added).firstOrDefault()?.added);
var list2 = query2.toList();
print('Descending');
for (var element in list2) {
print(element);
}
}
Collection<E> col<E>(Iterable<E> sequence) => Collection<E>(sequence);
List<MainItem> _getMainItems() {
var result = <MainItem>[];
var day = 0;
for (var i = 0; i < 3; i++) {
var subItems = <SubItem>[];
for (var j = 0; j < 3; j++) {
var subItem = SubItem(DateTime.now().subtract(Duration(days: day++)));
subItems.add(subItem);
}
var title = 'Item ${i}';
var item = MainItem(title, subItems);
result.add(item);
}
result.add(MainItem('Item w/o subitems', []));
return result;
}
class MainItem {
final String title;
final List<SubItem> subItem;
MainItem(this.title, this.subItem);
String toString() {
return '${title} : ${subItem}';
}
}
class SubItem {
final DateTime added;
SubItem(this.added);
String toString() {
return '${added}';
}
}
结果:
Ascending
Item w/o subitems : []
Item 2 : [2019-03-15 20:44:07.065185, 2019-03-14 20:44:07.065185, 2019-03-13 20:44:07.065185]
Item 1 : [2019-03-18 20:44:07.065185, 2019-03-17 20:44:07.065185, 2019-03-16 20:44:07.065185]
Item 0 : [2019-03-21 20:44:07.063184, 2019-03-20 20:44:07.064184, 2019-03-19 20:44:07.064184]
Descending
Item 0 : [2019-03-21 20:44:07.063184, 2019-03-20 20:44:07.064184, 2019-03-19 20:44:07.064184]
Item 1 : [2019-03-18 20:44:07.065185, 2019-03-17 20:44:07.065185, 2019-03-16 20:44:07.065185]
Item 2 : [2019-03-15 20:44:07.065185, 2019-03-14 20:44:07.065185, 2019-03-13 20:44:07.065185]
Item w/o subitems : []