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