Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将词典的内容复制到C#中的新词典?_C#_.net_Generics_Dictionary - Fatal编程技术网

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

如何将词典的内容复制到C#中的新词典?,c#,.net,generics,dictionary,C#,.net,Generics,Dictionary,如何将词典复制到另一个新词典,使它们不是同一个对象?假设您希望它们是单个对象,而不是对同一对象的引用,则将源词典传递到: Dictionary d=newdictionary(); 字典d2=新字典(d); “因此它们不是同一个对象。” 歧义比比皆是-如果您确实希望它们是对同一对象的引用: Dictionary<string, string> d = new Dictionary<string, string>(); Dictionary<string, stri

如何将
词典
复制到另一个
新词典
,使它们不是同一个对象?

假设您希望它们是单个对象,而不是对同一对象的引用,则将源词典传递到:

Dictionary d=newdictionary();
字典d2=新字典(d);
“因此它们不是同一个对象。”

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

Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = d;
Dictionary d=newdictionary();
字典d2=d;
(在上述操作之后更改
d
d2
都会影响这两种操作)

使用系统;
使用System.Collections.Generic;
班级计划
{
静态void Main(字符串[]参数)
{
字典优先=新字典()
{
{“1”,“1”},
{2”,“2”},
{“3”,“3”},
{“4”,“4”},
{“5”,“5”},
{“6”,“6”},
{“7”,“7”},
{“8”,“8”},
{“9”,“9”},
{“0”,“零”}
};
Dictionary second=新字典();
foreach(第一个.Keys中的字符串键)
{
第二,添加(键,第一个[键]);
}
第一个[“1”]=“新的”;
控制台写入线(第二个[“1”);
}
}

Amal答案的一行版本:

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

作为旁注,有一次我被绊倒了。如果使用此方法复制静态词典,则在副本中所做的更改仍将影响原始词典。可以找到其他方法
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"]);
    }
}
var second = first.Keys.ToDictionary(_ => _, _ => first[_]);