Best way to Sort lists in Flutter

huangapple go评论73阅读模式
英文:

Best way to Sort lists in Flutter

问题

我有两个列表,一个包含特定顺序中枚举的所有可能值(列表 A),第二个列表填充了其中一些枚举值/或空值/或全部(列表 B),但顺序是随机的。

我试图将列表 B 按照列表 A 的顺序排序。当数值缺失时,它们应该被跳过,但顺序应保持不变。

起初,我以为这很容易,但我无法在不弄乱代码的情况下处理它,我认为这可以更轻松地完成。

英文:

I have two lists, one containing all possible values of an enum in a special order (list A) and a second one which is filled with some of these enum values/or null/or all (list B) but the order is random.

What I am trying is to sort list B in the order of list A. When values are missing, they are skipped, but the order should stay the same.

In the first instance, I thought this is easy but I can‘t manage it without a mess of code and I think this could be done way easier.

答案1

得分: 1

为了在secondList中添加存在于firstList中的项目,此函数将执行以下操作:

List getMatchingItems() {
  List newSortedList = [];
  List<String> firstList = [
    "ENUM1",
    "ENUM2",
    "ENUM3",
    "ENUM4",
  ];
  List<String> secondList = [
    "ENUM2",
    "ENUM4",
    "ENUM5",
  ];

  for (var ennum in secondList) {
    if (firstList.contains(ennum)) {
      newSortedList.add(ennum);
    }
  }
  return newSortedList;
}
英文:

In order to add items in secondList that exists in firstList
this function will do so..

List getMatchingItems() {
  List newSortedList = [];
  List&lt;String&gt; firstList = [
    &quot;ENUM1&quot;,
    &quot;ENUM2&quot;,
    &quot;ENUM3&quot;,
    &quot;ENUM4&quot;,
  ];
  List&lt;String&gt; secondList = [
    &quot;ENUM2&quot;,
    &quot;ENUM4&quot;,
    &quot;ENUM5&quot;,
  ];

  for (var ennum in secondList) {
    if (firstList.contains(ennum)) {
      newSortedList.add(ennum);
    }
  }
  return newSortedList;
} 

huangapple
  • 本文由 发表于 2023年3月9日 17:37:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定