如何在 C# 中更新存储在字典中的值?
在 C# 中,字典是一种通常用来存储键/值对的泛型集合。在字典中,键不能为 null,但值可以为 null。键必须唯一。如果我们尝试使用重复的键,则不允许重复的键,并且编译器将引发异常。
如上所述,可以通过使用其键来更新字典中的值,因为每个值的键都是唯一的。
myDictionary[myKey] = myNewValue;
示例
让我们创建一个具有 ID 和名称的学生字典。现在,如果我们要把 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP