How do I convert from a Dictionary to a SortedDictionary using LINQ in C#?

You don't need LINQ, just some nifty extension methods:

public static IDictionary<TKey, TValue> Sort<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
    if(dictionary == null)
    {
        throw new ArgumentNullException("dictionary");
    }

    return new SortedDictionary<TKey, TValue>(dictionary);
}

public static IDictionary<TKey, TValue> Sort<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
{
    if(dictionary == null)
    {
        throw new ArgumentNullException("dictionary");
    }

    if(comparer == null)
    {
        throw new ArgumentNullException("comparer");
    }

    return new SortedDictionary<TKey, TValue>(dictionary, comparer);
}

Example usage:

var dictionary = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 0, "zero" }
};

foreach(var pair in dictionary.Sort())
{
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}

// 0: zero
// 1: one
// 2: two

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.


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());
    }
}

No LINQ is needed. SortedDictionary has a constructor to do the conversion.

public SortedDictionary<TKey,TValue> Convert<TKey,TValue>(Dictionary<TKey,TValue> map) {
  return new SortedDictionary<TKey,TValue>(map);
}