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

更新於: 04-Aug-2020

6K+ 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.