加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用类型T对List进行排序

发布时间:2020-12-15 20:01:01 所属栏目:百科 来源:网络整理
导读:我正在尝试对类型列表 T进行排序与泡沫排序.不幸的是我在比较未知类型的对象时遇到了问题. 到目前为止我尝试过的: public static void BubbleSortT(this ListT array){ for (int i = (array.Count - 1); i = 0; i--) { for (int j = 1; j = i; j++) { if (a
我正在尝试对类型列表< 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)
    {
        ...
    }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读