C#에서 사전은 일반적으로 키/값 쌍을 저장하는 데 사용되는 일반 컬렉션입니다. 사전에서 키는 null일 수 없지만 값은 null일 수 있습니다. 키는 고유해야 합니다. 중복 키를 사용하려고 하면 중복 키가 허용되지 않습니다. 그러면 컴파일러에서 예외가 발생합니다.
위에서 언급했듯이 사전의 값은 키를 사용하여 업데이트할 수 있습니다. 키는 모든 값에 대해 고유하기 때문입니다.
myDictionary[myKey] = myNewValue;
예시
아이디와 이름을 가지고 있는 학생들의 사전을 생각해 봅시다. 이제 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