Reputation: 15861
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?
Upvotes: 10
Views: 9171
Reputation: 1502
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
Upvotes: 2
Reputation: 108810
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.
Upvotes: 19