假设这是针对信用评级的,通常这是通过在CreditRating
类上设置一个“排序顺序”列来完成的,您可以使用该列对列表进行排序,然后再将其指定为下拉列表的数据源。
但是,一个快速的解决方法(基于有限的可能值)是按第一个字母升序排序,然后按字符串长度降序排序:
if(left[0] != right[0])
return left[0].CompareTo(right[0]);
else
return right.Length - left.Length;
如果您想更好地控制顺序,另一种解决方法是以“正确”顺序创建可能值的列表,然后使用它对列表进行排序:
public class MyComparer : IComparer<string>
{
private static readonly string[] Ratings = new [] {
"CC","C","CCC-","CCC","CCC+",
"B-","B","B+","BB-","BB","BB+","BBB-","BBB","BBB+",
"A-","A","A+","AA-","AA","AA+","AAA"};
// reverse the order so that any strings not found will be put at the end.
public int Compare(string left, string right)
{
return Array.IndexOf(Ratings, right).CompareTo(Array.IndexOf(Ratings, left));
}
}