I want something like a List<string>, but whenever I do an "Add", it keeps the list sorted.开发者_JAVA百科 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.
The SortedList class?
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);
}
}
}
SortedList: http://msdn.microsoft.com/en-us/library/ms132319.aspx
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.)
精彩评论