如何在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
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短