to sort a collection that I do not know what type does it have?

Is there a way in .NET that I can sort my collection when I do not know what types of objects at run time I will pass to this collection and also by avoiding Reflection.

any thoughts?

Answers


You do need some way of comparing elements. The usual way is to demand IComparable:

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

or use an IComparer, either for the Sorting method or the constructor:

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

Why can't you use an ArrayList collection?

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

Need Your Help

RGB accuracy problems with bufferedImage

java image jpeg bufferedimage javax.imageio

We find that there always exists some RGB accuracy problems whlie getting RGB from a jpeg file using bufferedImage in Java(ImageIO.read(file))..

Vagrant box and Docker provider: Titan and Kafka

docker vagrant apache-kafka titan

I have been recently introduced to the notion of Docker containers and found myself looking for one that runs Titan together with Kafka. I do not seem to be able to find what I need in Docker Hub a...