Sort a list of maps in Dart - Second Level Sort in Dart

痴心易碎 提交于 2020-05-28 12:55:48

问题


I have a list of maps like this:

var associations = [{'name': 'EG', 'description': 'Evil Genius'},
                    {'name': 'NaVi', 'description': 'Natus Vincere'}];

var members = [
{'associationName': 'EG', 'firstName': 'Bob', 'lastName': 'Dylan', 'email': 'bd@gmail.com'},
{'associationName': 'NaVi', 'firstName': 'John', 'lastName': 'Malkovich', 'email': 'jm@gmail.com'},
{'associationName': 'EG', 'firstName': 'Charles', 'lastName': 'Darwin', 'email': 'cd@gmail.com'}
];

I would like to write a code that would sort the list of members alphabetically by the last name first, then by the first name. Moreover, I would like to be able to find members whose lastnames start with a specifiedd letter. By example, with D, we would get Bob Dylan and Charles Darwin. I am able to manage it with a single map or a single list, but combining a list of maps makes it more difficult.

Thanks for your help.


回答1:


To sort :

members.sort((m1, m2) {
  var r = m1["lastName"].compareTo(m2["lastName"]);
  if (r != 0) return r;
  return m1["firstName"].compareTo(m2["firstName"]);
});

To filter :

members.where((m) => m['lastName'].startsWith('D'));



回答2:


List<Map> myList = [
  { 'name' : 'ifredom',age:23},
  { 'name' : 'JackMa',age:61},
  { 'name' : 'zhazhahui',age:48},
];

myList.sort((a, b) => (b.age).compareTo(a.age)); /// sort List<Map<String,dynamic>>

print(myList);


来源:https://stackoverflow.com/questions/22177838/sort-a-list-of-maps-in-dart-second-level-sort-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!