【发布时间】:2011-08-23 05:11:34
【问题描述】:
如何将Dictionary<string, string> 复制到另一个new Dictionary<string, string> 以使它们不是同一个对象?
【问题讨论】:
标签: c# .net generics dictionary
如何将Dictionary<string, string> 复制到另一个new Dictionary<string, string> 以使它们不是同一个对象?
【问题讨论】:
标签: c# .net generics dictionary
假设您的意思是希望它们成为单独的对象,而不是对同一对象的引用将源字典传递到 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 将同时影响两者)
【讨论】:
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[_]);
【讨论】:
var second = first.ToDictionary(kvp => k.Key, kvp => kvp.Value);
first.Keys.ToDictionary(_ 比first.ToDictionary(kvp=> k.Key 读得更好,因为它读起来更流畅,并且不需要变量名来描述意图(因此使用下划线/丢弃)。所以我的是first 的键作为字典,然后我查看最后一个参数,看到值只是键的值。您的带有丢弃的语法也适用:first.ToDictionary(_ => _.Key, _ => _.Value)