List<T>
(and SafeList
) have a great feature for fast lookups: BinarySearch
. However, the list needs to be sorted in order to use it. You could call Sort()
first, but that would give back all the performance you got with BinarySearch
. It’s better to just keep the list sorted all the time. Unfortunately, there is no function on IList<T>
, List<T>
, or SafeList
to efficiently insert an item into a list that’s already sorted. Today’s article presents an extension function that adds this functionality on to IList<T>
and even the non-generic IList
so your list will always be sorted for quick lookups with BinarySearch
. Read on for the code, unit tests, and a performance test showing the advantages you stand to gain.
Posts Tagged safelist
The first version of SafeList
tried to address a common problem: inserting and removing elements into a List<T>
while you loop over it. It had a lot of problems though and ended up being pretty much useless. Today’s article presents SafeList
2.0, a radically-improved version that really solves the problem so you can actually use it as a drop-in replacement for List<T>
. Read on for the details, the source code, and even the unit tests that prove it handles all the nasty corner cases for you!