排序我不知道它有什么类型的集合?

时间:2010-07-27 17:20:38

标签: c# collections

在.NET中我是否可以对我的集合进行排序,当我不知道运行时的哪些类型的对象时,我将传递给此集合并避免反射。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

你确实需要一些比较元素的方法。通常的方法是要求IComparable:

class MyCollection<T> where T : IComparable<T>
{
}

或使用IComparer,用于Sorting方法或构造函数:

class MyCollection<T> // where T : IComparable<T>
{
    void Sort(IComparer<T> comparer) 
    {
        if  (comparer.Compare(a, b) > 0) { ... }
    }
}

答案 1 :(得分:1)

为什么不能使用ArrayList集合?

ArrayList list = new ArrayList();
list.Add("R");
list.Add("B");
list.Add("G");
list.Sort();
//produces "B","G","R"

list.Clear();
list.Add(100);
list.Add(10);
list.Add(9);
list.Sort();
//produces 9,10,100