How to convert a Dictionary to a SortedDictionary?
In addition to general conversion (preserving types of key and values) I'm interested in swapping the keys and values as part of the conversion: have a Dictionary<string, double>
and I want to convert it to a SortedDictionary<double, string>
.
How do I do this using LINQ extension methods in C# 3.0?
Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.
In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements. The capacity of a Dictionary is the number of elements that Dictionary can hold.
We can use the OrderBy method to sort a SortedDictionary items. The OrderBy method takes a key name that items will be sorted based on.
Why use LINQ? There is a constructor for this:
new SortedDictionary<int, string>(existing);
You could add a ToSortedDictionary
- but I wouldn't bother...
Note: this is an answer to the title of the question (convert a Dictionary
to a SortedDictionary
for the same types, if you need additional step that OP is looking for - swap key and values in the process - as shown in the updated problem, see this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With