如何在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 爱生日祝福语简短独特