How do I copy the content of a dictionary to an new dictionary in C#?

前端 未结 3 652
温柔的废话
温柔的废话 2021-01-01 09:33

How can I copy a Dictionary to another new Dictionary so that they are not the same object?

相关标签:
3条回答
  • 2021-01-01 10:10
    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"]);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 10:18

    A one-line version of Amal's answer:

    var second = first.Keys.ToDictionary(_ => _, _ => first[_]);
    
    0 讨论(0)
  • 2021-01-01 10:21

    Assuming you mean you want them to be individual objects, and not references to the same object:

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

    "so that they are not the same object."

    Ambiguity abound - if you do actually want them to be references to the same object:

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

    (Changing either d or d2 after the above will affect both)

    0 讨论(0)
提交回复
热议问题