简体   繁体   中英

sort objects in a list by names which starts with the search string in dart

Let's say we have a class called Thing , which is defined as follows:

class Thing {
   final int id;
   final String name;

   Thing(this.id, this.name);
}

and we have a list of this class that is like this:

final List<Thing> things= [
   Thing(1, 'Black Car'),
   Thing(2, 'Red Car'),
   Thing(3, 'Car'),
   Thing(4, 'Green Car'),
   Thing(5, 'Car Yellow'),
   Thing(6, 'Car Blue'),
];

now we want to search in this list for some things using the word Car like this:

things.where(
    (thing) => thing.name.contains('Car')
    ).toList()

the result will be:

[
   Thing(1, 'Black Car'),
   Thing(2, 'Red Car'),
   Thing(3, 'Car'),
   Thing(4, 'Green Car'),
   Thing(5, 'Car Yellow'),
   Thing(6, 'Car Blue'),
]

now how can I sort this result by the things which names start with the search word Car , in other words, I want this to be the result:

   [
       Thing(3, 'Car'),
       Thing(5, 'Car Yellow'),
       Thing(6, 'Car Blue'),
       Thing(2, 'Red Car'),
       Thing(1, 'Black Car'),
       Thing(4, 'Green Car'),
    ]

thanks in advance.

You can use sort function to sort the list as you want. Here is a working sample:

class Thing {
  final int id;
  final String name;

  Thing(this.id, this.name);

  Map toJson() {
    Map data = {};
    data['id'] = id;
    data['name'] = name;
    return data;
  }
}

final List<Thing> things = [
  Thing(1, 'Black Car'),
  Thing(2, 'Red Car'),
  Thing(3, 'Car'),
  Thing(4, 'Green Car'),
  Thing(5, 'Car Yellow'),
  Thing(6, 'Car Blue'),
];

void main() async {
  List<Thing> myList =
      things.where((thing) => thing.name.contains('Car')).toList();
  myList
    ..sort((Thing a, Thing b) {
      int indexOfCarInA = a.name.indexOf('Car');
      int indexOfCarInB = b.name.indexOf('Car');
      if (indexOfCarInA < indexOfCarInB)
        return -1;
      else if (indexOfCarInA == indexOfCarInB) if (a.id <= b.id) return -1;
      return 1;
    });
  myList.forEach((element) {
    print(element.toJson());
  });

}

With List.sort , you give a priority when things start with "Car":

final filteredThings = things.where(
  (thing) => thing.name.contains('Car')
).toList();

filteredThings.sort((a, b) {
  if (a.startsWith('Car') && !b.startsWith('Car')) {
    return 1;
  }
  if (b.startsWith('Car') && !a.startsWith('Car')) {
    return -1;
  }
  return a.name.compareTo(b.name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM