如何在Dart语言中按字母顺序排序字符串列表?

11

我有4个公司,每个公司都有10多个分支机构。如果用户选择了一个公司,我需要使用showDialog显示所选的公司分支机构。到这里一切都按预期工作。我的问题是我无法按字母顺序排序List<String>

有什么办法可以在Dart中按字母顺序对字符串列表(List)进行排序吗?

List<String> _myBranchListName;

https://dev59.com/3lUL5IYBdhLWcg3w3LQH - Jordan Davies
@JordanDavies,您提供的解决方案适用于List<dynamics>,但不适用于List<String>,谢谢。 - Nick
@AlexanderFink,您提供的解决方案适用于List<dynamics>,但不适用于List<String>,谢谢。 - Nick
2个回答

44
  • Flutter是一个应用程序开发SDK。

  • Dart是一种通用编程语言。

  • Flutter应用程序是用Dart编写的。

  • 因此:

    如何在Flutter List<String>中按A到Z排序?

  • 将变成

    如何在Dart List<String>中按A到Z排序?

  • A到Z:被称为按字母顺序排序,因此:

    如何在Dart List<String>中按字母顺序排序?

  • List<String>:是一种字符串类型的列表,因此

    如何在Dart String List中按字母顺序排序?

  • 更多

    如何在Dart语言中按字母顺序对字符串列表进行排序?

代码:

main() {
  List<String> _myBranchListName= ['k branch', 'a branch', 'f branch'];

  _myBranchListName.sort();
  print(_myBranchListName);

  //[a branch, f branch, k branch]
}

更新

我有一个包含类“product”的自定义列表,其中“product”包含变量“title”,现在我需要根据标题对我的列表进行排序,如何处理?''' comment

sort方法:

根据比较函数指定的顺序对此列表进行排序。

如果省略了compare,则默认的List实现将使用Comparable.compare。

比较器可能会将对象视为相等(返回零),

即使它们是不同的对象。 sort功能不保证稳定,因此将作为相等进行比较的不同对象可能以任何顺序出现在结果中

  • 你的代码(警告:我没有测试过这段代码,我需要您的反馈):

produts.sort((a, b) => a.title.compareTo(b.title));


1
在我的项目中,我有超过100个与Jordan和Alexander提供的其他解决方案配合使用的List<dynamic>。我只有一个List<String>,但我忘记使用基本的.sort()方法。谢谢你提供的信息。 - Nick
2
我有一个自定义列表,其中包含类产品和产品包含变量标题,现在我需要根据标题对我的列表进行排序,该如何做? - Midhilaj
1
@Midhilaj请查看答案中的更新。 - Mohamed Elrashid
1
请注意,两个字符串的默认比较是区分大小写的,这意味着以小写字母"a"开头的字符串将排在以大写字母"Z"开头的字符串之后。在我的情况下,我不想要这样,所以我像这样修复了它:a.toLowerCase().compareTo(b.toLowerCase() - stefanS

5

List包含一个名为sort的方法,该函数将按字母顺序(从a到z)对列表进行排序。

我为您创建了一个函数,以使该过程更加清晰:

List<String> sort(List<String> _myBranchListName){    // This function take List of strings and return it organized alphabetically
 // List<String> _myBranchListName = ["B branch", "C branch" , "A branch"]; // example of input
  print(_myBranchListName);   // will show the result in the run log
  _myBranchListName.sort();
  print(_myBranchListName);   // will show the result in the run log
  return _myBranchListName;
}

从技术角度讲,您只需要使用_myBranchListName.sort()来对数组进行排序。


1
谢谢,.sort() 是解决方案。 - Nick
嗨@Nick,如果这个答案解决了你的问题,请点击“此答案有用”复选框。这将显示你对帮助的感激之情。 - Guy Luz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接