c# - 优化 list<T>.Sort(Comparer)

标签 c# generics sorting collections

我有一个存储丢失的整数的列表。 我不喜欢默认的 List.Sort() 工作,因为我希望列表按实际 int 的大小排序。 到目前为止我有这个:

哦,整数存储在字符串中,例如“1234”。这是我无法改变的。

public class IntComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
            // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the 
                // lengths of the two strings.
                //
                int xInt = Convert.ToInt32(x);
                int yInt = Convert.ToInt32(y);

                if (x > y)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return 1;
                }
                else if (xInt == yInt)
                {
                    return 0;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.


        //
                return -1;
            }
        }
    }
}

但据我所知,这是冒泡排序,对吗? 我应该实现什么?快排?另外,我可能需要帮助来编写它。

哦,我的列表包含不到 2000 个元素,这些元素将数字存储在字符串中

另外,我这样称呼我的 IComparer:

IntComparer intSort = New IntComparer();
List<T>.Sort(intSort);

最佳答案

假设你想按存储为字符串的整数的值排序,你可以简单地做这样的事情:

numbers.Sort((x,y) => Int32.Parse(x).CompareTo(Int32.Parse(y)));

关于c# - 优化 list<T>.Sort(Comparer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771779/

相关文章:

java - 关于Java中的接口(interface)和泛型的问题: type mismatch error

c# - 使用具有泛型类型的解析方法?

java - Java 中的泛型和排序

C# 根据另一个列表字符串对类属性列表进行排序

在 Clojure 中对拉丁字符串进行排序

c# - 在 C# 中获取 Excel 单元格背景颜色的问题

c# - .NET Core2.0 bundleconfig.json 不工作

c# - MVC 6 更改返回内容类型

Java数组: Making numbers into separated,排列的数字,输出问题

c# - DataGrid只选择一行中的单元格