Please enable Javascript for better experience...
Working with dictionary in c#
By Rahul Kumar Jha | Oct 14, 2015 | In Articles | Total Views [ 3425 ]
Taged In
(1 Like)
Rate

In this article you will see how can we get key and values from a dictionary object in C#.

Introduction

Getting keys and values from dictionary is easy task. You can get it with the help of KeyValuePair object or from simple collection. I will explain this in below example. In the example, I have created a dictionary which has integer key with list of string collection as value. Let's see step by step.

Example Code

Declare a dictionary with key of integer type and value of list type of string  Dictionary<int, List<string>>()

Dictionary

//Dictionary item
Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>{
{1,new List<string>{"Dee", "X", "23"}},
{2,new List<string>{"Joe", "X", "24"}}
};

Getting values by key

void GetDictionaryValue()
{
//To fetch values on the basis of key
foreach (int key in dictionary.Keys)
{
var details = dictionary[key];
Console.WriteLine("Details are: {Name=" + details[0] + ", Class=" + details[1] + ", Roll Number=" + details[2]);
}
}

Getting key and values from dictionary

void GetKeyAndValueFromDict()
{
//To fetch keys and values from dictionary
foreach (KeyValuePair<int, List<string>> item in dictionary)
{
var key = item.Key;
var value = item.Value;
Console.WriteLine("Details are: {Name=" + value[0] + ", Class=" + value[1] + ", Roll Number=" + value[2]);
}
}

Hope this helps you.

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