英文:
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<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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论