简体   繁体   English

如何对 dart 中的无序值列表进行排序?

[英]How to sort a list of unordered values in dart?

Below is the program I tried but couldn't get expected results,以下是我尝试但无法获得预期结果的程序,

void main() {
  List data = ['Jan-21','Feb-21','Aug-21','Jan-22','Jun-21','Sept-22','Mar-21','Apr-22'];
  data.sort((a,b){
    return a.compareTo(b);
  });
  print(data.toString());
  //output - [Apr-22, Aug-21, Feb-21, Jan-21, Jan-22, Jun-21, Mar-21, Sept-22]
  //expected - [Jan-21, Feb-21, Mar-21, Aug-21, Jan-22, Apr-22, Jun-21, Sept-22]
}

I need to sort a list of "months-year" data as per the order in which they actually come ,我需要按照它们实际出现的顺序对“月-年”数据列表进行排序,

for this list [Jan-21,Feb-21,Aug-21,Jan-22,Jun-21,Sept-22,Mar-21,Apr-22]对于此列表[Jan-21,Feb-21,Aug-21,Jan-22,Jun-21,Sept-22,Mar-21,Apr-22]

The output expected is [Jan-21, Feb-21, Mar-21, Aug-21, Jan-22, Apr-22, Jun-21, Sept-22] output 预计为[Jan-21, Feb-21, Mar-21, Aug-21, Jan-22, Apr-22, Jun-21, Sept-22]

List<String> getSortedDates(List<String> dates){

  //Formatting for acceptable DateTime format
  DateFormat formatter = DateFormat("MMM-yy");

  //Mapping to convert into appropriate dateFormat
  List<DateTime> _formattedDates = dates.map(formatter.parse).toList();

  //Apply sort function on formatted dates
  _formattedDates.sort();

  //Mapping through sorted dates to return a List<String> with same formatting as passed List's elements
  return _formattedDates.map(formatter.format).toList();

}

You can sort directly by overriding the sort function to sort by datetime.您可以通过覆盖排序 function 以按日期时间排序来直接排序。

 DateFormat formatter = DateFormat("MMM-yy");
 data.sort((a, b) => formatter.parse(a)
       .compareTo(formatter.parse(b)));

You have to convert to date and use intl and then you can sort them您必须转换为日期并使用intl然后您可以对它们进行排序

Note: you have set month name length to prevent the pattern problem注意:您已设置月份名称长度以防止模式问题

jun => MMM君 => 嗯

sept => MMMM九月 => MMMM

    void main() {
  List data = [
    'Jan-21',
    'Feb-21',
    'Aug-21',
    'Jan-22',
    'Jun-21',
//     'Sept-22', // you have set month name length same to prevent the pattern problem
    'Mar-21',
    'Apr-22'
  ];
  data.sort((a, b) {
    var formattedDateA = intl.DateFormat("MMM-yy").parse(a);
    var formattedDateB = intl.DateFormat("MMM-yy").parse(b);
    
    return formattedDateA.compareTo(formattedDateB);
  });
  print(data.toString());
  //output - [Jan-21, Feb-21, Mar-21, Jun-21, Aug-21, Jan-22, Apr-22]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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