如何在 Dart 中将 List<Event> 转换为 Map<DateTime, List<Event>>?
How to convert List<Event> to Map<DateTime, List<Event>> in Dart?
我想在 Dart 中将 List 转换为 Map,如下所示。有什么好的方法吗?
class Event {
const Event(this.date, this.title);
final DateTime date;
final String title;
}
List<Event> eventList = [
Event(DateTime(2021, 1, 1), "buy milk"),
Event(DateTime(2021, 1, 1), "go to gym"),
Event(DateTime(2021, 1, 2), "running"),
];
// I want to convert map as follows.
Map<DateTime, List<Event>> eventDayMap = {
DateTime(2021, 1, 1): [Event(DateTime(2021, 1, 1), "buy milk"), Event(DateTime(2021, 1, 1), "go to gym")],
DateTime(2021, 1, 2): [Event(DateTime(2021, 1, 2), "running")]
};
假设每个 DateTime
只存储日期而不存储时间,我会使用 ??=
默认为每个日期添加一个空列表,然后我只添加列表元素:
var eventDayMap = <DateTime, List<Event>>{};
for (var event in eventList) {
(eventDayMap[event.date] ??= []).add(event);
}
如果您正在存储时间信息但想按日期索引,那么您必须先规范化键:
DateTime dateOnly(DateTime dateTime) {
if (dateTime.isUtc) {
return DateTime.utc(dateTime.year, dateTime.month, dateTime.day);
} else {
return DateTime(dateTime.year, dateTme.month, dateTime.day);
}
}
var eventDayMap = <DateTime, List<Event>>{};
for (var event in eventList) {
(eventDayMap[dateOnly(event.date)] ??= []).add(event);
}
如果您希望事件按时间排序:
for (var list in eventDayMap.values) {
list.sort((event1, event2) => event1.date.compareTo(event2.date));
}
我想在 Dart 中将 List 转换为 Map,如下所示。有什么好的方法吗?
class Event {
const Event(this.date, this.title);
final DateTime date;
final String title;
}
List<Event> eventList = [
Event(DateTime(2021, 1, 1), "buy milk"),
Event(DateTime(2021, 1, 1), "go to gym"),
Event(DateTime(2021, 1, 2), "running"),
];
// I want to convert map as follows.
Map<DateTime, List<Event>> eventDayMap = {
DateTime(2021, 1, 1): [Event(DateTime(2021, 1, 1), "buy milk"), Event(DateTime(2021, 1, 1), "go to gym")],
DateTime(2021, 1, 2): [Event(DateTime(2021, 1, 2), "running")]
};
假设每个 DateTime
只存储日期而不存储时间,我会使用 ??=
默认为每个日期添加一个空列表,然后我只添加列表元素:
var eventDayMap = <DateTime, List<Event>>{};
for (var event in eventList) {
(eventDayMap[event.date] ??= []).add(event);
}
如果您正在存储时间信息但想按日期索引,那么您必须先规范化键:
DateTime dateOnly(DateTime dateTime) {
if (dateTime.isUtc) {
return DateTime.utc(dateTime.year, dateTime.month, dateTime.day);
} else {
return DateTime(dateTime.year, dateTme.month, dateTime.day);
}
}
var eventDayMap = <DateTime, List<Event>>{};
for (var event in eventList) {
(eventDayMap[dateOnly(event.date)] ??= []).add(event);
}
如果您希望事件按时间排序:
for (var list in eventDayMap.values) {
list.sort((event1, event2) => event1.date.compareTo(event2.date));
}