如何在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 婆婆高寿祝福语大全简短