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)
(改变上述任何一个d或d2之后都会影响两者)
Amal 的答案的一行版本:
var second = first.Keys.ToDictionary(_ => _, _ => first[_]);
Run Code Online (Sandbox Code Playgroud)
小智 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)
| 归档时间: |
|
| 查看次数: |
40521 次 |
| 最近记录: |