c# - 对类型为 T 的列表进行排序

标签 c# list sorting

我正在尝试对 <T> 类型的列表进行排序用冒泡排序。不幸的是,我在比较未知类型的对象时遇到了问题。

到目前为止我尝试了什么:

public static void BubbleSort<T>(this List<T> array)
{
    for (int i = (array.Count - 1); i >= 0; i--)
    {
        for (int j = 1; j <= i; j++)
        {
            if (array[j - 1] > array[j]) // issue here
            {
                var temp = array[j - 1];
                array[j - 1] = array[j];
                array[j] = temp;
            }
        }
    }
}

最佳答案

如果除了默认比较之外你不需要任何东西,你可以使用:

// TODO: Rename the parameter...
public static void BubbleSort<T>(this List<T> array)
{
    IComparer<T> comparer = Comparer<T>.Default;
    ...
    if (comparer.Compare(array[j - 1], array[j]) > 0)
    {
        ...
    }
}

或者允许自定义比较:

public static void BubbleSort<T>(this List<T> array, IComparer<T> comparer)
{
    ...
    if (comparer.Compare(array[j - 1], array[j]) > 0)
    {
        ...
    }
}

或者限制T实现 IComparable<T> 的类型:

public static void BubbleSort<T>(this List<T> array) where T : IComparable<T>
{
    ...
    if (array[j - 1].CompareTo(array[j]) > 0)
    {
        ...
    }
}

请注意,在 T 上添加约束这里意味着任何调用者需要知道他们使用的类型参数需要实现IComparable<T> ...它使它在编译时更安全,代价是将约束传播到调用链中。 (一种选择是允许没有比较器的受限版本和比较器的无约束版本。)

关于c# - 对类型为 T 的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993664/

相关文章:

c# - 加入声明和分配或不加入...这是个问题

c# - 如何从 Canvas 中的隐藏代码打开图像并让用户在此图像上绘图

C# .NET 单元测试 - 如何停止执行捕获

algorithm - 修改 LIST 使得一个元素大于之前所有元素的总和

java - 按多个字段对 Java bean 进行排序的正确方法

javascript - react 虚拟网格排序图标

c# - 为什么 EmguCV 高斯模糊可能不会返回与 OpenCV 高斯模糊相同的结果?

java - 打印出列表中的某些元素

python - (Python)我可以将函数本身而不是它们的值存储在列表中吗

python - 将列表的一部分与Python中的完整列表进行比较