【问题标题】:How do I convert from a Dictionary to a SortedDictionary using LINQ in C#?如何在 C# 中使用 LINQ 从 Dictionary 转换为 SortedDictionary?
【发布时间】:2010-10-01 21:22:45
【问题描述】:

如何将 Dictionary 转换为 SortedDictionary?

除了一般转换(保留键和值的类型)之外,我对交换键和值作为转换的一部分感兴趣:有一个Dictionary<string, double>,我想将它转换为SortedDictionary<double, string>

如何在 C# 3.0 中使用 LINQ 扩展方法来做到这一点?

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

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

    new SortedDictionary<int, string>(existing);
    

    您可以添加 ToSortedDictionary - 但我不会打扰...


    注意:这是对问题标题的回答(如果您需要 OP 正在寻找的其他步骤,请将同一类型的 Dictionary 转换为 SortedDictionary - 在此过程中交换键和值 -如更新问题所示,见this answer

    【讨论】:

    • 刚刚意识到我没有在原始问题中反引号。
    • 我很高兴这是公认的答案,尽管它没有回答 OP 想要问的问题。这绝对是标题问题的正确答案。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      这个答案解决了在过程中交换键和值的转换。

      您似乎在寻求一种优雅的方式来获取Dictionary&lt;TKey,TValue&gt; 并将其转换为SortedDictionary&lt;TValue,TKey&gt;(注意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());
          }
      }
      

      【讨论】:

        【解决方案4】:

        你不需要 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
        

        【讨论】:

          【解决方案5】:

          使用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
          

          【讨论】:

            猜你喜欢
            • 2012-12-30
            • 1970-01-01
            • 2010-10-17
            • 2015-12-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多