How to read all items of a Dictionary in C#

Reading Dictionary Items

The Dictionary is a collection. We can use the foreach loop to go through all the items and read them using the Key and Value properties.

foreach (KeyValuePair<string, Int16> author in AuthorList)  
{  
    Console.WriteLine("Key: {0}, Value: {1}",  
    author.Key, author.Value);  
}
The following code snippet creates a new dictionary, reads all of its items, and displays them on the console.
public void CreateDictionary()  
{  
    // Create a dictionary with string key and Int16 value pair  
    Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
    AuthorList.Add("Mahesh Chand", 35);  
    AuthorList.Add("Mike Gold", 25);  
    AuthorList.Add("Praveen Kumar", 29);  
    AuthorList.Add("Raj Beniwal", 21);  
    AuthorList.Add("Dinesh Beniwal", 84);   
  
    // Read all data  
    Console.WriteLine("Authors List");   
  
    foreach (KeyValuePair<string, Int16> author in AuthorList)  
    {  
        Console.WriteLine("Key: {0}, Value: {1}",  
            author.Key, author.Value);  
    }  
}  

Output

 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.