如何在C#中使用LINQ从Dictionary转换为SortedDictionary?

Guy*_*Guy 28 c# linq dictionary

我有一个Dictionary<string, double>,我想将其转换为SortedDictionary<double, string>.如何在C#3.0中使用LINQ扩展方法执行此操作?

编辑:当Marc和Jared回答时,通用尖括号不在原始问题中.

Mar*_*ell 49

编辑此答案是在编辑之前; 要获得更新问题的答案,请参阅此回复.

为什么要使用LINQ?有一个构造函数:

new SortedDictionary<int, string>(existing);
Run Code Online (Sandbox Code Playgroud)

你可以一个ToSortedDictionary- 但我不会打扰......

  • 我很高兴这是公认的答案,尽管它没有回答 OP 打算提出的问题。这绝对是标题问题的正确答案。 (2认同)

Jar*_*Par 8

不需要LINQ.SortedDictionary有一个构造函数来进行转换.

public SortedDictionary<TKey,TValue> Convert<TKey,TValue>(Dictionary<TKey,TValue> map) {
  return new SortedDictionary<TKey,TValue>(map);
}
Run Code Online (Sandbox Code Playgroud)


And*_*are 5

看起来好像你要求一种优雅的方式来Dictionary<TKey,TValue>把它变成一个SortedDictionary<TValue,TKey>(注意它的值Dictionary现在是关键SortedDictionary).我没有看到任何答案解决这个问题.

您可以创建一个如下所示的扩展方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您的应用程序代码如下所示:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)