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

37

如何将字典转换为排序字典?

除了一般的转换(保留键和值的类型)外,我还希望在转换过程中交换键和值:有一个Dictionary<string, double>,我想将其转换为一个SortedDictionary<double, string>

如何使用C# 3.0中的LINQ扩展方法实现?

5个回答

69

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

new SortedDictionary<int, string>(existing);
你可以添加一个ToSortedDictionary,但我觉得没必要...... 注意:这是针对问题标题的回答(将同类型的Dictionary转换为SortedDictionary),如果您需要OP正在寻找的额外步骤 - 在过程中交换键和值 - 如在更新的问题中所示,请参见此答案

刚刚意识到我在原问题中没有用反引号引用尖括号。 - Guy
2
虽然这个答案并没有回答 OP 想要问的问题,但我很高兴它被接受了。它绝对是这个问题的正确答案。 - Profesor Caos

10

不需要使用LINQ。SortedDictionary有一个构造函数可以完成转换。

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

6
这个答案讲述了在转换过程中交换键和值的方法。
看起来你正在寻找一种优雅的方式,将一个`Dictionary`转换为一个`SortedDictionary`(请注意,现在`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;
    }
}

你的应用程序代码将使用该辅助方法交换键和值,并像这样使用SortedDictionary的常规构造函数:

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

1

你不需要LINQ,只需要一些巧妙的扩展方法:

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

使用示例:

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
使用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);
}

使用示例:

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

反转和排序的示例(有关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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接