In this article you will see how can we get key and values from a dictionary object in C#.
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.
Declare a dictionary with key of integer type and value of list type of string Dictionary<int, List<string>>()
//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"}}
};
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]);
}
}
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.