How is List <string> but preserves string order?

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

+2


source to share


6 answers


You can try SortedList or SortedDictionary . Both will do what you want, but with slightly different implementations. You can find the differences highlighted here .



+11


source


SortedList class?



+3


source


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);
        }

    }
}

      

+2


source


+1


source


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

which would have an AddAndSort (T t) method added

it won't be interchangable with a normal IList however, but it does what you need.

+1


source


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.)

+1


source







All Articles