How is List <string> but preserves string order?
You can try SortedList or SortedDictionary . Both will do what you want, but with slightly different implementations. You can find the differences highlighted here .
source to share
Use list <T> and call List <T>. Grade .
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 can also expand the <T> list, override Add, choose 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);
}
}
}
source to share
You can extend List
to let the method Add
do a binary search to find the correct insertion location and then add it there. This should provide better performance than overriding Add
to add and then sort the list. (Btw, Sort
uses Quicksort, which doesn't necessarily give high performance for this case.)
source to share