Search code examples
.netlistsortedlist

How do I create a List<T> from a SortedList<int, T>?


I'm working with .net 3.5, and I have this:

SortedList<int, BrainTickTransition>

And I want one of these:

List<BrainTickTransition>

Is there a quick way to do this without having to copy all of the values from the SortedList?


Solution

  • The values need to be copied, because there is no way to share the memory between a List<TValue> and a SortedList<TKey,TValue>.

    I assume you want a List<TValue> containing the values without caring about the keys, which you can do with:

    sortedList.Values.ToList();
    

    But if you just need an IList<TValue> (as opposed to the concrete class List<TValue>) you can directly use the Values property and thus avoid creating a copy.

    Of course these solutions differ in their semantic when the original collection gets modified. The List<TValue> copy will not reflect the changes, whereas the IList<TValue> referenced by the Values property, will reflect the changes, even if you assign it to another variable.