如何将字典的内容复制到C#中的新字典?

han*_*ler 24 .net c# generics dictionary

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

Jay*_*ymz 64

假设您的意思是希望它们是单个对象,而不是对同一对象的引用:

Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = new Dictionary<string, string>(d);
Run Code Online (Sandbox Code Playgroud)

"所以他们不是同一个对象."

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

Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = d;
Run Code Online (Sandbox Code Playgroud)

(改变上述任何一个dd2之后都会影响两者)

  • 就像一个旁注,一些让我绊倒的东西.如果使用此方法复制静态字典,则复制中所做的更改仍将影响原始字典 (2认同)
  • 可以找到另一种方法/sf/ask/9771471/?answertab=votes#tab -顶部 (2认同)

Zod*_*man 8

Amal 的答案的一行版本:

var second = first.Keys.ToDictionary(_ => _, _ => first[_]);
Run Code Online (Sandbox Code Playgroud)

  • 好奇:你为什么不这样做呢?`var Second = first.ToDictionary(kvp =&gt; k.Key, kvp =&gt; kvp.Value);` (2认同)

小智 7

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"]);
    }
}
Run Code Online (Sandbox Code Playgroud)