This answer addresses conversion with swapping keys and values in the process.
It seems as though you are asking for an elegant way to take a Dictionary<TKey,TValue>
and turn that into a SortedDictionary<TValue,TKey>
(note that the value of the Dictionary
is now the key of the SortedDictionary
).
You could create an extension method that swaps keys and values of the dictionary into another dictionary:
static class Extensions
{
public static Dictionary<TValue, TKey>
AsInverted<TKey, TValue>(this Dictionary<TKey, TValue> source)
{
var inverted = new Dictionary<TValue, TKey>();
foreach (KeyValuePair<TKey, TValue> key in source)
inverted.Add(key.Value, key.Key);
return inverted;
}
}
And your application code would use that helper method to swap keys and values and use regular constructor of SortedDictionary
like this:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
var dict = new Dictionary<String, Double>();
dict.Add("four", 4);
dict.Add("three", 3);
dict.Add("two", 2);
dict.Add("five", 5);
dict.Add("one", 1);
var sortedDict = new SortedDictionary<Double, String>(dict.AsInverted());
}
}