Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create list from multiple lists with a property is equal

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?.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading