【问题标题】:How do I copy the content of a dictionary to an new dictionary in C#?如何将字典的内容复制到 C# 中的新字典?
【发布时间】:2011-08-23 05:11:34
【问题描述】:

如何将Dictionary<string, string> 复制到另一个new Dictionary<string, string> 以使它们不是同一个对象?

【问题讨论】:

    标签: c# .net generics dictionary


    【解决方案1】:

    假设您的意思是希望它们成为单独的对象,而不是对同一对象的引用将源字典传递到 destination's constructor:

    Dictionary<string, string> d = new Dictionary<string, string>();
    Dictionary<string, string> d2 = new Dictionary<string, string>(d);
    

    “这样它们就不是同一个对象了。”

    歧义比比皆是 - 如果您确实希望它们是对同一对象的引用:

    Dictionary<string, string> d = new Dictionary<string, string>();
    Dictionary<string, string> d2 = d;
    

    (在上面更改d 或d2 将同时影响两者)

    【讨论】:

    • 作为旁注,曾经让我绊倒的东西。如果你使用这个方法复制一个静态字典,那么在副本中所做的更改仍然会影响原来的
    • 另一种方法可以找到stackoverflow.com/questions/139592/…
    【解决方案2】:
    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> first = new Dictionary<string, string>()
            {
                {"1", "One"},
                {"2", "Two"},
                {"3", "Three"},
                {"4", "Four"},
                {"5", "Five"},
                {"6", "Six"},
                {"7", "Seven"},
                {"8", "Eight"},
                {"9", "Nine"},
                {"0", "Zero"}
            };
    
            Dictionary<string, string> second = new Dictionary<string, string>();
            foreach (string key in first.Keys)
            {
                second.Add(key, first[key]);
            }
    
            first["1"] = "newone";
            Console.WriteLine(second["1"]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      Amal 答案的单行版本:

      var second = first.Keys.ToDictionary(_ => _, _ => first[_]);
      

      【讨论】:

      • 好奇:你为什么不这样做呢? var second = first.ToDictionary(kvp =&gt; k.Key, kvp =&gt; kvp.Value);
      • 当性能不重要并且我面临不同的语法可能性时,我会选择我认为更易于阅读的版本。我相信明确使用first.Keys.ToDictionary(_ 比first.ToDictionary(kvp=&gt; k.Key 读得更好,因为它读起来更流畅,并且不需要变量名来描述意图(因此使用下划线/丢弃)。所以我的是first 的键作为字典,然后我查看最后一个参数,看到值只是键的值。您的带有丢弃的语法也适用:first.ToDictionary(_ =&gt; _.Key, _ =&gt; _.Value)
      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      相关资源
      最近更新 更多