如何在C#中更新存储在Dictionary中的值?
在C#中,Dictionary是通用集合,通常用于存储键/值对。在字典中,键不能为null,但值可以为null。键必须唯一。如果我们尝试使用重复键,则不允许重复键,然后编译器将引发异常。
如上,字典中的值可以通过使用其键来更新,因为键对于每个值都是唯一的。
myDictionary[myKey] = myNewValue;
示例
让我们看一下具有id和name的学生的字典。现在,如果要将ID为2的学生的名称从“Mrk”更改为“Mark”。
using System;
using System.Collections.Generic;
namespace DemoApplication{
class Program{
static void Main(string[] args){
Dictionary<int, string> students = new Dictionary<int, string>{
{ 1, "John" },
{ 2, "Mrk" },
{ 3, "Bill" }
};
Console.WriteLine($"Name of student having id 2: {students[2]}");
students[2] = "Mark";
Console.WriteLine($"Updated Name of student having id 2: {students[2]}");
Console.ReadLine();
}
}
}输出结果
上面的代码的输出是-
Name of student having id 2: Mrk Updated Name of student having id 2: Mark
热门推荐
10 幼儿祝福语押韵句子简短
11 公司开年仪式祝福语简短
12 生日贺卡祝福语 简短独特
13 中考祝福语简短卡片大全
14 婆婆生日祝福语简短的
15 叔叔生日祝福语简短励志
16 祖国七十华诞简短祝福语
17 庆双节祝福语简短
18 初八祝福语简短语