dart - 对 Dart 中的对象列表进行排序
问题描述
我正在尝试使用以下函数对名为“posts”的对象列表进行排序。它似乎没有像我预期的那样工作,我不知道为什么。在调用函数之前,“帖子”中的标题值是 66666666666,新的,Luke Kady,Rory 的溜冰场,新的帖子。按标题排序后:66666666666,Luke Kady,新的,新的职位,Rory 的溜冰场。还尝试添加.toLowerCaase()
标题并得到相同的结果。
void sortPosts(String sortBy) {
if (sortBy == "Title") {
posts.sort((a, b) => a.title[0].compareTo(b.title[0]));
} else {
posts.sort((a, b) => a.price.compareTo(b.price));
}
}
解决方案
您可以手动检查 compareTo 值并决定要做什么。
在下面的示例中,我们使用反射(镜像),因此我们可以指定一个属性(反射不是必需的,也可以避免)。
以下是一些帮助您入门的代码:
class Post {
String title;
String author;
Post({this.title = "N/A", this.author = "N/A"});
// partially applicable sorter
static Function(Post, Post) sorter(int sortOrder, String property) {
int handleSortOrder(int sortOrder, int sort) {
if (sortOrder == 1) {
// a is before b
if (sort == -1) {
return -1;
} else if (sort > 0) {
// a is after b
return 1;
} else {
// a is same as b
return 0;
}
} else {
// a is before b
if (sort == -1) {
return 1;
} else if (sort > 0) {
// a is after b
return 0;
} else {
// a is same as b
return 0;
}
}
}
return (Post a, Post b) {
switch (property) {
case "title":
int sort = a.title.compareTo(b.title);
return handleSortOrder(sortOrder, sort);
case "author":
int sort = a.author.compareTo(b.author);
return handleSortOrder(sortOrder, sort);
default:
break;
}
};
}
// sortOrder = 1 ascending | 0 descending
static void sortPosts(List<Post> posts, {int sortOrder = 1, String property = "title"}) {
switch (property) {
case "title":
posts.sort(sorter(sortOrder, property));
break;
case "author":
posts.sort(sorter(sortOrder, property));
break;
default:
print("Unrecognized property $property");
}
}
}
void main() {
List<Post> posts = [
new Post(title: "bart loves ice cream", author: "bart"),
new Post(title: "alex loves ice cream", author: "alex"),
new Post(title: "carl loves ice cream", author: "carl")
];
print("---Sorted by title Ascending(default) order---");
Post.sortPosts(posts);
posts.forEach((p) => print(p.title));
print("---Sorted by title Descending order----");
Post.sortPosts(posts, sortOrder: 0);
posts.forEach((p) => print(p.title));
print("---Sorted by author Ascending order---");
Post.sortPosts(posts, property: "author");
posts.forEach((p) => print(p.author));
}
输出:
---Sorted by title Ascending(default) order---
alex loves ice cream
bart loves ice cream
carl loves ice cream
---Sorted by title Descending order----
carl loves ice cream
bart loves ice cream
alex loves ice cream
---Sorted by author Ascending order---
alex
bart
carl
推荐阅读
- rxjs - rxjs - 使用布尔可观察流值过滤流事件
- java - int [](整数数组)与Java中的对象类关系
- php - 如何使用 ACF 过滤掉值?
- python - Scipy Dendrogram - 如何在给定一组标签的情况下显示叶节点的“纯度”?
- python - 如何将 Pandas 数据帧从一个文件读取到另一个文件
- bash - 如何在 Windows 的 gitbash 中运行“make”命令?
- javascript - 我可以将返回的直播流对象保存在本地存储中吗
- python - 列出(数据)并返回仅包含 |x−μ| 的那些数据条目 x 的列表
这个问题让我对如何解释 x 有点困惑,到目前为止我做了如下工作:
import numpy as np def keep(data, M): array_DATA = np.a
- asp.net - updatepanel.update() 后网格视图不刷新
- r - 致命:尝试从新 Mac(Catalina)连接到红移数据库时,主机没有 pg_hba.conf 条目