如何将字典转换为排序字典?
除了一般的转换(保留键和值的类型)外,我还希望在转换过程中交换键和值:有一个Dictionary<string, double>
,我想将其转换为一个SortedDictionary<double, string>
。
如何使用C# 3.0中的LINQ扩展方法实现?
如何将字典转换为排序字典?
除了一般的转换(保留键和值的类型)外,我还希望在转换过程中交换键和值:有一个Dictionary<string, double>
,我想将其转换为一个SortedDictionary<double, string>
。
如何使用C# 3.0中的LINQ扩展方法实现?
为什么要使用LINQ?这里有一个构造函数:
new SortedDictionary<int, string>(existing);
你可以添加一个ToSortedDictionary
,但我觉得没必要...... 注意:这是针对问题标题的回答(将同类型的Dictionary
转换为SortedDictionary
),如果您需要OP正在寻找的额外步骤 - 在过程中交换键和值 - 如在更新的问题中所示,请参见此答案。不需要使用LINQ。SortedDictionary有一个构造函数可以完成转换。
public SortedDictionary<TKey,TValue> Convert<TKey,TValue>(Dictionary<TKey,TValue> map) {
return new SortedDictionary<TKey,TValue>(map);
}
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());
}
}
你不需要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
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