Sort on insert using compare function

I am trying to sort data of type T in a container with two properties of T. This is potentially a lot of data, so I would prefer the sorting to happen on insert. I looked at both List and SortedList , but both of them do not provide the functionality I need.

Does C # provide a container that allows both sorting upon insertion and sorting my comparison function? I would like to avoid sorting the insertion insert, such as List.Sort , and avoid the overhead of using data as a key and value for a SortedList .

+6
source share
2 answers

If you are using .NET 4, you can use SortedSet with a custom IComparer<T> . The disadvantage is that it will not allow you to have several equal elements. You need it?

I don’t understand why you want to sort by insert only because you have a lot of data. Do you need it to be sorted before you finish the insert? If not, I would expect one end at the end (via List.Sort ) to be as efficient as sorting in its own way.

+6
source

If you want to keep the same sort order all the time, you can use SortedList<K,V> or SortedDictionary<K,V> and pass to the constructor IComparer<K> .

If you need a different sort orders in a single container, you can use List<T> and pass the IComparer<T> method of Sort .

Since you are probably storing reference types, I would not worry too much about using elements of both keys and values. You just save the links.

Another option is to implement your own binary tree structure.

+2
source

Source: https://habr.com/ru/post/920827/


All Articles