如何在C#中使用LINQ将字典从Dictionary转换为SortedDictionary? [英] How do I convert from a Dictionary to a SortedDictionary using LINQ in C#?
问题描述
如何将字典转换为SortedDictionary?
How to convert a Dictionary to a SortedDictionary?
除了常规转换(保留键和值的类型)外,我还想将键和值交换为转换:具有 Dictionary< string,double>
,我想将其转换为 SortedDictionary< double,string>
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>
.
如何在C#3.0中使用LINQ扩展方法来做到这一点?
How do I do this using LINQ extension methods in C# 3.0?
推荐答案
为什么要使用LINQ?对此有一个构造函数:
Why use LINQ? There is a constructor for this:
new SortedDictionary<int, string>(existing);
您可以添加一个 ToSortedDictionary
-但我不会打扰...
You could add a ToSortedDictionary
- but I wouldn't bother...
注意:这是对问题标题的答案(转换为将字典
转换为相同类型的 SortedDictionary
,如果需要OP查找的其他步骤-在过程中交换键和值-如图所示在更新的问题中,请参阅此答案。
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.
这篇关于如何在C#中使用LINQ将字典从Dictionary转换为SortedDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!