如何在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