在c#中按字母顺序对任意属性排序通用列表

时间:2011-12-02 20:26:47

标签: c# .net list sorting alphanumeric

是否可以在c#中以字母数字的形式对任意属性进行通用列表排序?如果问题不明确,请告诉我,我会想出一个例子。

提前致谢

注意:我发现这个链接可以做到但不是按字母顺序排列的。谁能帮我吗? http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/

2 个答案:

答案 0 :(得分:1)

这是一个快速的字母数字排序(也可以用于其他种类的数字)。

C#字母数字排序http://www.dotnetperls.com/alphanumeric-sorting

public class AlphanumComparatorFast : IComparer
{
    public int Compare(object x, object y)
    {
    string s1 = x as string;
    if (s1 == null)
    {
        return 0;
    }
    string s2 = y as string;
    if (s2 == null)
    {
        return 0;
    }

    int len1 = s1.Length;
    int len2 = s2.Length;
    int marker1 = 0;
    int marker2 = 0;

    // Walk through two the strings with two markers.
    while (marker1 < len1 && marker2 < len2)
    {
        char ch1 = s1[marker1];
        char ch2 = s2[marker2];

        // Some buffers we can build up characters in for each chunk.
        char[] space1 = new char[len1];
        int loc1 = 0;
        char[] space2 = new char[len2];
        int loc2 = 0;

        // Walk through all following characters that are digits or
        // characters in BOTH strings starting at the appropriate marker.
        // Collect char arrays.
        do
        {
        space1[loc1++] = ch1;
        marker1++;

        if (marker1 < len1)
        {
            ch1 = s1[marker1];
        }
        else
        {
            break;
        }
        } while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

        do
        {
        space2[loc2++] = ch2;
        marker2++;

        if (marker2 < len2)
        {
            ch2 = s2[marker2];
        }
        else
        {
            break;
        }
        } while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

        // If we have collected numbers, compare them numerically.
        // Otherwise, if we have strings, compare them alphabetically.
        string str1 = new string(space1);
        string str2 = new string(space2);

        int result;

        if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
        {
        int thisNumericChunk = int.Parse(str1);
        int thatNumericChunk = int.Parse(str2);
        result = thisNumericChunk.CompareTo(thatNumericChunk);
        }
        else
        {
        result = str1.CompareTo(str2);
        }

        if (result != 0)
        {
        return result;
        }
    }
    return len1 - len2;
    }
}

使用

var unordered = new[] { "100F", "50F", "SR100", "SR9" };
var ordered = unordered.OrderBy(s => s, new AlphanumComparatorFast());

这是一篇关于这个问题的好文章:

为人类排序:自然排序顺序http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

答案 1 :(得分:0)

假设通过“字母数字”来表示这样的排序:

01a
02a
02b
0a
1a
1b
a
b
c
...

您可以使用LINQ的OrderBY方法:

IEnumerable<T> myObjects = myObjects.OrderBy(x => x.SomeProperty);

基于PO输入的编辑:

不幸的是,这不会按照你想要的方式运作(100F 50F SR100 SR9转到50F 100F SR9 SR100)。但您可以使用重载的OrderBy并实现所需的IComparer