我有一个组合框来显示我的数据库中的数据(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)
然后我将 All
和 Other
添加到我的数据表结果中。但是如何设置All
和Others
总是第一个和最后一个呢?
只要您的集合是 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/
我是一名优秀的程序员,十分优秀!