
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add key-value pair in C# Dictionary
To add key-value pair in C# Dictionary, firstly declare a Dictionary.
IDictionary<int, string> d = new Dictionary<int, string>();
Now, add elements with KeyValuePair.
d.Add(new KeyValuePair<int, string>(1, "TVs")); d.Add(new KeyValuePair<int, string>(2, "Appliances")); d.Add(new KeyValuePair<int, string>(3, "Mobile"));
After adding elements, let us display the key-value pair.
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { IDictionary<int, string> d = new Dictionary<int, string>(); d.Add(new KeyValuePair<int, string>(1, "TVs")); d.Add(new KeyValuePair<int, string>(2, "Appliances")); d.Add(new KeyValuePair<int, string>(3, "Mobile")); d.Add(new KeyValuePair<int, string>(4, "Tablet")); d.Add(new KeyValuePair<int, string>(5, "Laptop")); d.Add(new KeyValuePair<int, string>(6, "Desktop")); d.Add(new KeyValuePair<int, string>(7, "Hard Drive")); d.Add(new KeyValuePair<int, string>(8, "Flash Drive")); foreach (KeyValuePair<int, string> ele in d) { Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value); } } }
Output
Key = 1, Value = TVs Key = 2, Value = Appliances Key = 3, Value = Mobile Key = 4, Value = Tablet Key = 5, Value = Laptop Key = 6, Value = Desktop Key = 7, Value = Hard Drive Key = 8, Value = Flash Drive
- Related Questions & Answers
- Add a key value pair to dictionary in Python
- Accessing Key-value in a Python Dictionary
- JavaScript - Sort key value pair object based on value?
- Add key and value into StringDictionary in C#
- Appending a key value pair to an array of dictionary based on a condition in JavaScript?
- Get key from value in Dictionary in Python
- JavaScript - Convert an array to key value pair
- Add key and value into OrderedDictionary collection in C#
- Add a value to Pair Tuple in Java
- Get key with maximum value in Dictionary in Python
- How to add key/value pairs in SortedList in C#?
- Get the number of key/value pairs in the Dictionary in C#
- Java Program to remove key value pair from HashMap?
- What is possible key/value delimiter in Python dictionary?
- Add the specified key and value into the ListDictionary in C#
Advertisements