我有串列包含幾個Timestamp.toDate()如下
List MyList= [
2022-06-09 10:01:56.874
2022-06-09 11:02:22.874 // it has the same previous days,months but difference times
2022-06-09 12:03:22.874 // it has the same previous days,months but difference times too
2023-06-09 11:00:56.874 // it has the same previous days,months but difference Years
]
現在,我如何洗掉所有具有相同天數、數月數的元素,至少保留這些天的一個舊元素(所選元素將是最舊的時間)并且與年份相同,
所以我希望輸出如下
List MyList= [
2022-06-09 10:01:56.874 // i will keep this element because it is old one
2022-06-09 11:02:22.874 // i will delete this because it has same previous day and month
2022-06-09 12:03:22.874 // i will delete this because it has same previous day and month too
2023-06-09 11:00:56.874 // we have here same previous days and month but i will keep it because it has difference year
]
所以決賽
List MyList= [
2022-06-09 10:01:56.874
2023-06-09 11:00:56.874
]
我有像這樣的大元素的大串列,任何人都可以告訴我如何過濾我的串列嗎?謝謝
uj5u.com熱心網友回復:
這可以解決問題:
List<DateTime> myList = [
DateTime(2022, 06, 09, 10, 01),
DateTime(2022, 06, 09, 11, 02),
DateTime(2022, 06, 09, 12, 03),
DateTime(2023, 06, 09, 10, 01),
];
// Important that the list is sorted first..
// You might be able to skip the sorting, as your list already seemed to be sorted
myList.sort();
final res = myList
.where(
(e) => e == myList.firstWhere((f) => e.year == f.year && e.month == f.month && e.day == f.day),
)
.toList();
print(myList);
print(res);
將列印:
[2022-06-09 10:01:00.000, 2022-06-09 11:02:00.000, 2022-06-09 12:03:00.000, 2023-06-09 10:01:00.000]
[2022-06-09 10:01:00.000, 2023-06-09 10:01:00.000]
飛鏢墊:
https://dartpad.dev/bc6cc0ee81d89b56eb358c12a973fafa
uj5u.com熱心網友回復:
我相信這會給我想要的結果,盡管我不確定是否有更有效的方法來做到這一點。這也假設串列已排序。
var result = groupBy(MyList,
(DateTime datetime) => DateFormat('dd-MM-yyyy').format(datetime))
.values
.expand((element) => [element.first])
.toList();
對于此處使用的方法,您將需要這些匯入
import "package:collection/collection.dart";
import 'package:intl/intl.dart';
uj5u.com熱心網友回復:
我認為您對日期中的時間部分不感興趣,您只對日期(年、月、日)感興趣,因此我們可以圍繞洗掉時間部分的技巧構建整個解決方案:
第一步:將日期轉換為DateTime()物件,例如:
List<DateTime> dateTimes = [
DateTime.parse('2022-06-09 10:01:56.874'),
DateTime.parse('2022-06-09 11:02:22.874'),
DateTime.parse('2022-06-09 12:03:22.874'),
DateTime.parse('2023-06-09 11:00:56.874'),
];
第二步:洗掉時間部分dateTimes:
final List<DateTime> dates = dateTimes.map((dateTime) => DateTime(dateTime.year,dateTime.month,dateTime.day)).toList();
第三步:定義一個串列來保存過濾后的輸出:
final List<DateTime> filteredDates = [];
第四步:在串列上回圈dates,對于每個日期,檢查它是否存在于過濾串列中,如果存在,則忽略它,如果不存在,則添加它。
請注意,它會起作用,因為當我們從dateTimes具有相同年份、月份和日期的所有日期中洗掉時間部分時,它變得等價。
for (DateTime date in dates) {
if (!filteredDates.contains(date)) {
filteredDates.add(date);
}
}
就是這樣!,輸出:
[2022-06-09 00:00:00.000, 2023-06-09 00:00:00.000]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488080.html
