生成新的嵌套列表
Generate new nested list
假设我有一个日期对象列表。我想按月将它们分成一个新列表,这个列表将添加到另一个列表中。最终成为List<List<DateTime>>
.
{
[2020-12-25],
[2020-12-25],
[2020-11-24],
[2020-10-23]
}
to
[
[2020-12-25,2020-12-25],
[2020-11-24],
[2020-10-23]
]
我在沙盒中尝试过的
void test(List<DateTime> datelist) {
List<List<DateTime> mainList = [];
datelist.forEach((date){
if(mainlist.isEmpty == true) {
List<DateTime> temp = [];
temp.add(date);
mainList.add(temp);
} else {
mainList.forEach((monthList) {
if(monthList.first.month == date.month) {
monthList.add(date);
} else {
List<DateTime> temp = [];
temp.add(date);
mainList.add(temp);
}
});
}
});
}
但是命中错误:Uncaught Error: concurrent modification during iteration: Instance of 'JSArray<List<DateTime>>
.
像这样的东西应该可以工作:
void main() async {
var dates = <DateTime>[
DateTime(2020, 12, 25),
DateTime(2020, 12, 25),
DateTime(2020, 11, 24),
DateTime(2020, 10, 23)];
var monthMap = Map<int, List<DateTime>>();
for (final date in dates) {
var list = monthMap[date.month];
if (list == null) {
list = [date];
monthMap[date.month] = list;
} else {
list.add(date);
}
}
List<List<DateTime>> mainList = monthMap.values.toList();
print("[" + mainList.map((e) {
return "[${e.map((d) => "${d.year}-${d.month}-${d.day}").join(", ")}]";
}).join(", ") + "]");
}
假设我有一个日期对象列表。我想按月将它们分成一个新列表,这个列表将添加到另一个列表中。最终成为List<List<DateTime>>
.
{
[2020-12-25],
[2020-12-25],
[2020-11-24],
[2020-10-23]
}
to
[
[2020-12-25,2020-12-25],
[2020-11-24],
[2020-10-23]
]
我在沙盒中尝试过的
void test(List<DateTime> datelist) {
List<List<DateTime> mainList = [];
datelist.forEach((date){
if(mainlist.isEmpty == true) {
List<DateTime> temp = [];
temp.add(date);
mainList.add(temp);
} else {
mainList.forEach((monthList) {
if(monthList.first.month == date.month) {
monthList.add(date);
} else {
List<DateTime> temp = [];
temp.add(date);
mainList.add(temp);
}
});
}
});
}
但是命中错误:Uncaught Error: concurrent modification during iteration: Instance of 'JSArray<List<DateTime>>
.
像这样的东西应该可以工作:
void main() async {
var dates = <DateTime>[
DateTime(2020, 12, 25),
DateTime(2020, 12, 25),
DateTime(2020, 11, 24),
DateTime(2020, 10, 23)];
var monthMap = Map<int, List<DateTime>>();
for (final date in dates) {
var list = monthMap[date.month];
if (list == null) {
list = [date];
monthMap[date.month] = list;
} else {
list.add(date);
}
}
List<List<DateTime>> mainList = monthMap.values.toList();
print("[" + mainList.map((e) {
return "[${e.map((d) => "${d.year}-${d.month}-${d.day}").join(", ")}]";
}).join(", ") + "]");
}