- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to update the value stored in a Dictionary in C#?
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary, the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed if we try to use duplicate key then compiler will throw an exception.
As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.
myDictionary[myKey] = myNewValue;
Example
Let’s take a dictionary of students having id and name. Now if we want to change the name of the student having id 2 from "Mrk" to "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(); } } }
Output
The output of the above code is −
Name of student having id 2: Mrk Updated Name of student having id 2: Mark
Advertisements