C#中的自定义字符串比较

我想在C#中实现自定义字符串IComparer并将其应用于ComboBox。

实际结果

如果我将ComboBoxSorted属性设置为true ,则输出为:

 A AA AAA B BB BBB 

通缉结果

排序算法的通缉行为如下(金融开发人员将理解为什么:)):

 AAA AA A BBB BB B 

有可能吗? 这里需要排序算法吗?

PS:我不需要完整的代码答案,我只需要了解它是如何完成的。

编辑

这是关于信用评级。 我在我的问题中省略了一些内容。 评级必须按此顺序排序:

 XXX XX+ XX XX- X+ X X- 

X in ('A','B','C')'A' > 'B' > 'C'

假设这是用于信用评级,通常这是通过在CreditRating类上设置“排序顺序”列来完成的,您可以使用该列对列表进行排序,然后将其指定为下拉列表的数据源。

但是,快速解决方法(基于有限的可能值)将按升序的第一个字母排序,然后按字符串降序的长度排序:

 if(left[0] != right[0]) return left[0].CompareTo(right[0]); else return right.Length - left.Length; 

如果您想要更多地控制订单,另一种解决方法是以“正确”顺序创建可能值的列表,然后使用它来对列表进行排序:

 public class MyComparer : IComparer { 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)); } } 

这是一个主要实现的版本:

 public class MyComparer : IComparer { public int Compare(string x, string y) { //todo null checks on input var pairs = x.Zip(y, (a, b) => new { x = a, y = b }); foreach (var pair in pairs) { int value = pair.x.CompareTo(pair.y); if (value != 0) return value; } //if we got here then either they are the same, //or one starts with the other return y.Length.CompareTo(x.Length); //note x and y are reversed here } } 

因此,这使用Zip从每个相应的字符串中获取字符对,直到结束,如果它们不相等则返回适当的值。 如果它超过了那个,那么一个字符串从另一个字符串开始。 对于传统的字符串比较,我们只是按照与输入参数相同的顺序比较长度。 由于我们基本上是根据长度反转顺序,请注意xy在最后一行交换。 这颠倒了比较逻辑。

编写IComparer,使其占用字符串,但每个字符进行比较,

 if A[0] == B[0] go to the next character. if B[1] == null or A[1] < B[1], return A < B. if A[1] == null or B[1] < A[1], return B < A. if equal...continue as needed