Please enable Javascript for better experience...
Different way of adding items in Dictionary in c#
By Rahul Kumar Jha | Jul 10, 2016 | In Tips | Total Views [ 8596 ]
Taged In
(3 Like)
Rate

You can add multiple items in a Dictionary either using Add() method or during object creation (if all items are available).

Introduction

If you want to add items in dictionary, you can either use Dictionary<tkey, tvalue>.Add() method or during object creation (if all items are available). If all items are not available, in that case you should use Add() method for the same.

Unfortunately we don't have AddRange() as there is no meaning of Range for associative container. Dictionary is an associative container.

Adding items/value during object creation

Let's create an object of dictionary and add key, values in it during initialization.

 Dictionary<int, string> dictionary = new Dictionary<int, string>()
            {
                {1, "Item one"},
                {2, "Item two"}
            };

You cannot add duplicate key in dictionary. Means you cannot write
dictionary.Add("one", "Value is one");
dictionary.Add("one", "Value is two");
The value in dictionary can be null for reference types but key cannot be null or duplicate.

Adding items/value using Add() method

You can use Add() method to add some items in dictionary.

            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            dictionary.Add(1, "Item one");
            dictionary.Add(1, "Item two");

Thanks for reading this article. Will write more soon...

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors