tags:

views:

159

answers:

6

I want something like a List<string>, but whenever I do an "Add", it keeps the list sorted. Any ideas?

+1  A: 

SortedList: http://msdn.microsoft.com/en-us/library/ms132319.aspx

popester
+11  A: 

You can try a SortedList or a SortedDictionary. Both will do what you need to do, but with slightly differing implementations. You can find the differences highlighted here.

Nikhil
Note that SortedList and SortedDictionary cannot be accessed by index and do not implement the IList<T> interface. Both are more like dictionaries than lists. Specifically, you cannot do SortedList<string>.Add(someString) -- you have to pass in a key and a value. This is very unnatural for a list-like interface.
itowlson
+3  A: 

The SortedList class?

Kaleb Brasee
+2  A: 

Use List< T > and call List< T >.Sort.

List<string> dinosaurs = new List<string>();

dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");     

Console.WriteLine("\nSort");
dinosaurs.Sort();

EDIT: You could also extend List< T >, override Add, pick one.

ExtendedList:

public class ExtendedList<T> : List<T>
{
    public new void Add(T t)
    {
        base.Add(t);
        base.Sort();
    }
}

ExtendedList with BinarySearch:

public class ExtendedList<T> : List<T>
{
    public new void Add(T t)
    {
        int index = base.BinarySearch(t);
        if (index < 0)
        {
            base.Insert(~index, t);
        }

    }
}
rick schott
I thought of that, but I don't want the sort overhead each time I access the list
JoelFan
You do understand that whatever you use to automatically sort will have overhead right?
rick schott
+1  A: 

You could create your own class, MySortList, that implements IList, and your own interface IMySort

Which would have an added method of AddAndSort(T t)

this wouldn't be interchangable with normal IList however, but it does do what you need to.

PostMan
It actually _would_ work if your implementation of `Add` called `AddAndSort`. And because you're implementing IList, it _would_ be interchangeable with IList... that's the point of separating the interface from the implementation. You wouldn't need IMySort however.
Nader Shirazie
Yes but IList does not implement AddAndSort, hence the extra interface. Unless you ignored AddAndSort, and on each add, sort it. Then it would be interchangable with IList
PostMan
+1  A: 

You could extend List so that the Add method does a binary search to find the correct insertion location, and then add it in there. This should give better performance than overriding Add to add and then sort the list. (Btw, Sort uses Quicksort, which doesn't necessarily give great performance for this case.)

David Johnstone