如何在 C# 中将字典的内容复制到新字典
本文关键字:字典 复制 新字典 | 更新日期: 2023-09-27 17:56:20
如何将Dictionary<string, string>
复制到另一个new Dictionary<string, string>
,使它们不是同一个对象?
假设您希望它们是单独的对象,而不是对同一对象的引用,则将源字典传递到目标的构造函数中:
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
都会影响两者)
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"]);
}
}
Amal回答的单行版本:
var second = first.Keys.ToDictionary(_ => _, _ => first[_]);