开发者

Sort String Data Numerically (ASP.NET C#)

I've got a gridview with column containing the following rows of data:

    1
    2a
    2b
    6
    8a
    10a

The header of the column has a sortExpression so I can click to sort it

If I do sort this data, I get it in this order:

    1
    10a
    2a
    2b
    6
    8a

..where the 10a row comes up because of the 1

I want it to sort numerically, but my values are strings. The data needs to sort by number and then by the lette开发者_C百科r at the end (if a letter is there)

How can I do this for my data the being pulled back from a datasource? Keep in mind that this is in a gridview.


If you have a list of strings then you can sort them using a custom comparison. Here is some code for it:

public static void NumericalSort(List<string> l)
{
    Regex rgx = new Regex("([^0-9]*)([0-9]+)");
    l.Sort((a, b) =>
    {
        var ma = rgx.Matches(a);
        var mb = rgx.Matches(b);
        for (int i = 0; i < ma.Count; ++i)
        {
            int ret = ma[i].Groups[1].Value.CompareTo(mb[i].Groups[1].Value);
            if (ret != 0)
                return ret;

            ret = int.Parse(ma[i].Groups[2].Value) - int.Parse(mb[i].Groups[2].Value);
            if (ret != 0)
                return ret;
        }

        return 0;
    });
}

static void Main(string[] args)
{
    List<string> l = new string[] { "1", "2a", "2b", "6", "8a", "10a" }.ToList();

    NumericalSort(l);

    foreach (var item in l)
        Console.WriteLine(item);
}


split the number and string and you can achieve what you want


CodeProject has one that I use occasionally.

http://www.codeproject.com/KB/recipes/csnsort.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜