I want something like a List<string>, but whenever I do an "Add", it keeps the list sorted. Any ideas?
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.
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);
}
}
}
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.
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.)