C#中的自定义字符串比较 [英] Custom string Comparison in C#

查看:191
本文介绍了C#中的自定义字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement a custom string IComparer in C# and apply it to a ComboBox.

实际结果

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

If I set the ComboBox's Sorted property to true, the output is :

A
AA
AAA
B
BB
BBB

想要的结果

排序算法的所需行为如下(金融开发人员将理解原因:)):

The wanted behavior of the sorting algorithm is the following (financial developers will understand why :) ) :

AAA
AA
A
BBB
BB
B

问题

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

Is it possible to do it ? Are sorting algorithms needed here ?

PS:我不需要代码的完整答案,我只需要知道如何实现即可..

PS : I don't need a complete answer with code, i just need an idea of how it might be done ..

编辑

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

This is about credit ratings. I've omitted something in my question. The ratings have to be sorted in this order :

XXX
XX+
XX
XX-
X+
X
X-

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

推荐答案

假设这是信用评级,通常通过在CreditRating类上具有排序顺序"列来完成,您可以使用该列对列表进行排序在将其分配为下拉菜单的数据源之前.

Assuming this is for credit ratings, normally this is done by having a "sort order" column on the CreditRating class that you could use to sort the list before assigning it as the data source of the drop-down.

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

But, a quick workaround (based on the limited possible values) would be to sort by the first letter ascending, then by the length of the string descending:

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

如果要进一步控制顺序,另一种解决方法是按正确"顺序创建可能值的列表,然后使用该列表对列表进行排序:

Another workaround if you want more control over the order is to create a list of possible values in the "right" order and then use that to sort the list:

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));
    }
}

这篇关于C#中的自定义字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆