My row lists:
List rowlist = [Student(name: 'John',age: 12),
Student(name: 'Kity',age: 13),
Student(name: 'Micle',age: 14),
Student(name: 'Jack',age: 12),
Student(name: 'Cha',age: 13),
Student(name: 'Duc',age: 13),
Student(name: 'Ran',age: 12)]
Expected result:
List result = [
[
Student(name: 'John',age: 12),
Student(name: 'Jack',age: 12),
Student(name: 'Ran',age: 12),
],
[
Student(name: 'Kity',age: 13),
Student(name: 'Cha',age: 13),
Student(name: 'Duc',age: 13),
],
[
Student(name: 'Micle',age: 14),
]
]
I need to create a new list of list wherein each list is added by Student with age field is equal. What is the best way for the result?.
>Solution :
If you use the collection package. You can use the groupListsBy method to group all of the students by age.
Map<int, List<Student>> result = rowlist.groupListsBy((student) => student.age);
The above however, returns the data as a Map<int, List<Student>. You can convert this to a List<List<Student>> by calling .values.toList().
List<List<Student>> result = rowlist.groupListsBy((student) => student.age).values.toList();
Complete example:
import 'package:collection/collection.dart';
void main() {
List<Student> rowlist = [
Student(name: 'John', age: 12),
Student(name: 'Kity', age: 13),
Student(name: 'Micle', age: 14),
Student(name: 'Jack', age: 12),
Student(name: 'Cha', age: 13),
Student(name: 'Duc', age: 13),
Student(name: 'Ran', age: 12),
];
List<List<Student>> result =
rowlist.groupListsBy((student) => student.age).values.toList();
print(result);
}
class Student {
final String name;
final int age;
const Student({required this.name, required this.age});
@override
String toString() => 'Student(name: $name, age: $age)';
}