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

Far*_*res 11 c# sorting string

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

实际结果

如果我将ComboBox's Sorted属性设置为true,则输出为:

A
AA
AAA
B
BB
BBB
Run Code Online (Sandbox Code Playgroud)

通缉结果

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

AAA
AA
A
BBB
BB
B
Run Code Online (Sandbox Code Playgroud)

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

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

编辑

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

XXX
XX+
XX
XX-
X+
X
X-
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*rvy 6

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

public class MyComparer : IComparer<string>
{
    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
    }
}
Run Code Online (Sandbox Code Playgroud)

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


D S*_*ley 2

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

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

if(left[0] != right[0])
    return left[0].CompareTo(right[0]);
else
    return right.Length - left.Length;
Run Code Online (Sandbox Code Playgroud)

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

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));
    }
}
Run Code Online (Sandbox Code Playgroud)