简体   繁体   English

Listview项目排序

[英]Listview item sort

I have several columns in a listview but I am just so dummb to think up a logical sorting method to both sort items out alphabetically and numerically. 我在列表视图中有几列,但我真是愚蠢,无法想出一种逻辑排序方法来按字母顺序和数字顺序对项目进行排序。 Because in case of numerical values I'd like a column's content such as: 因为在使用数字值的情况下,我希望查看列的内容,例如:

111    
13   
442  
23   
214

to be: 成为:

13  
23  
111  
214  
442

My current sorting class looks like this: 我当前的排序类如下所示:

class itemsorter:IComparer
{ 
    public int compare (object a, object b)
    {
       return string.compare(((lvitem)a).text,((lvitem)b).text));
    }
}   

Parse your Strings to numbers before doing the comparison, in which case you can simply return the difference of the 2 numbers as your result from the compare method. 在进行比较之前,将Strings解析为数字,在这种情况下,您可以简单地将两个数字的差返回为compare方法的结果。

As it sounds like you still want to sort both alphabetical and numerical values, this would have to be a combined, hybrid approach with the above - such that numbers are sorted against numbers, and alphabetical values with alphabetical. 听起来您仍然想同​​时对字母和数字值进行排序,因此必须将其与上述方法组合使用,从而使数字与数字进行排序,而字母值与字母进行排序。 You'd just need to choose which takes precedence, such that either numerical or alphabetical values always come first - necessary to maintain a stable and reflexive sort. 您只需要选择优先顺序,就可以始终使用数字或字母值,这对于保持稳定和反身的排序很有必要。 (For example, if a is a number, and b is a non-number, return 1. If a is a non-number, and b is a number, return -1. Else, they must be of equal types, and then you can defer to the type-specific sorting.) (例如,如果a是一个数字, b是一个非数字,则返回1。如果a是一个非数字,并且b是一个数字,则返回-1。否则,它们必须是相同的类型,然后您可以按照类型进行排序。)

As ziesemer said, you can take my sample code as below, hope this will give you a hand. 正如ziesemer所说,您可以按照以下方式获取我的示例代码,希望这能对您有所帮助。

class itemsorter : IComparer
{
    public int compare(object a, object b)
    {
        int resultA, resultB;
        bool markA = int.TryParse(((lvitem)a).text, out resultA);
        bool markB = int.TryParse(((lvitem)b).text, out resultB)

        // They are number.
        if (markA && markB)
        {
            if (resultA > resultB)
                return 1;
            else if (resultA < resultB)
                return -1;
            else
                return 0;
        }


        // a can convert to number,
        // b can't.
        if (markA && !markB)
        {
            return 1;
        }

        // b can convert to number,
        // a can't.

        if(!markA && markB)
        {
            return -1;
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM