How do I create a List<T> from a SortedList<int, T>?
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.