37

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?

0

5 Answers 5

69

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.

2
  • Just realized that I didn't back-quote the angle brackets in my original question.
    – Guy
    Jan 16, 2009 at 20:00
  • 2
    I'm glad this is the accepted answer, despite it not answering what OP had intended to ask. It is definitely the right answer to the title question. Jun 15, 2017 at 14:17
10

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

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

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
0

Inversion using ToDictionary:

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

    return dictionary.ToDictionary(pair => pair.Value, pair => pair.Key);
}

Example usage:

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

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

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

Example of inverting and sorting (see my other answer for the definition of Sort):

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.