Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 968
Almo Avatar asked Dec 08 '11 22:12

Almo


2 Answers

This Works:

myList = new List<string>(mySortedList.Values);

(Credit to the comment by @Jon).
The new List will never see subsequent changes to the sortedList. This is perfect for a scenario where SortedList was just for temp usage, or where the Sorted is for historic reference.

However, the answer by @CodesInChaos doesn't
Does Not Work:

myList = mySortedList.Values.ToList();

ToList() fails with with exception: IList<string> does not contain a definition for ToList

like image 67
Guy Avatar answered Oct 09 '22 09:10

Guy


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.

like image 18
CodesInChaos Avatar answered Oct 09 '22 10:10

CodesInChaos