gpt4 book ai didi

c# - 如何将(1,11,12,2,All,Others)排序为(All,1,2,11,12,Others)?

转载 作者:太空宇宙 更新时间:2023-11-03 18:16:21 27 4
gpt4 key购买 nike


我有一个组合框来显示我的数据库中的数据(varchar)。数据总是“1,2,3,4, others”,当我显示它排序的数据时:

1
10
11
12
2
3
4
All
Others

如何使下拉菜单看起来像:

All
1
2
3
4
10
11
12
Others

在 SQL 中,我尝试 ORDER BY CAST(priorityNum AS UNSIGNED INTEGER) 然后我将 AllOther 添加到我的数据表结果中。但是如何设置AllOthers总是第一个和最后一个呢?

最佳答案

只要您的集合是 IEnumerable,您就可以使用自定义比较器方法调用 OrderBy。你的比较器看起来像这样:

class myStringComparer: IComparer<string> {
public int Compare(string a, string b) {
if (a == b) return 0;
if (a == "All" || b == "Others") return -1;
if (a == "Others" || b == "All") return 1;
return int.Parse(a) - int.Parse(b);
}
}

如果发现意外数据(除“全部”、“其他”或数字之外的任何数据),这只会抛出异常。在尝试整数解析之前,您可能想要添加额外的逻辑。

现在,您可以在列表/集合上调用 .OrderBy(new myStringComparer())。请注意,OrderBy 仅可用于 IEnumerable 对象(这包括您可以放在 foreach 循环中的任何内容,例如数组、列表等).

关于c# - 如何将(1,11,12,2,All,Others)排序为(All,1,2,11,12,Others)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com