DEV Community

mohamed Tayel
mohamed Tayel

Posted on

1

Enumerating Dictionary Keys

In this article, we’ll explore how to enumerate dictionary keys while working with a collection of collections. To make it engaging, let's take a new example where we manage a collection of universities categorized by countries. Each country is a key in a dictionary, and the value is a list of universities in that country.


Key Concepts

  1. Dictionary Keys Enumeration:

    • A dictionary allows us to store data as key-value pairs. The Keys property is used to enumerate all the keys in the dictionary.
  2. Checking Key Existence:

    • The ContainsKey method ensures that we don’t access a key that doesn’t exist in the dictionary.
  3. Accessing and Processing Values:

    • The value corresponding to a key is accessed using square bracket syntax, which in this example, is a list of universities.
  4. LINQ for Filtering Results:

    • LINQ provides methods like Take to process collections effectively.

Full Code Example

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Dictionary of countries and their respective universities
        var universities = new Dictionary<string, List<University>>
        {
            {
                "USA",
                new List<University>
                {
                    new University("MIT", "Massachusetts"),
                    new University("Stanford University", "California"),
                    new University("Harvard University", "Massachusetts"),
                    // Add more universities if needed
                }
            },
            {
                "UK",
                new List<University>
                {
                    new University("University of Oxford", "Oxford"),
                    new University("University of Cambridge", "Cambridge"),
                    new University("Imperial College London", "London"),
                    // Add more universities if needed
                }
            }
        };

        // Display available countries
        Console.WriteLine("Available countries:");
        foreach (var country in universities.Keys)
        {
            Console.WriteLine(country);
        }

        // Ask the user to select a country
        Console.WriteLine("\nEnter a country:");
        string selectedCountry = Console.ReadLine();

        // Check if the selected country exists in the dictionary
        if (universities.ContainsKey(selectedCountry))
        {
            Console.WriteLine($"\nTop universities in {selectedCountry}:");

            // Retrieve and display universities in the selected country
            foreach (var university in universities[selectedCountry].Take(5))
            {
                Console.WriteLine($"- {university.Name}, located in {university.Location}");
            }
        }
        else
        {
            Console.WriteLine("Country not found.");
        }
    }
}

// University class definition
class University
{
    public string Name { get; set; }
    public string Location { get; set; }

    public University(string name, string location)
    {
        Name = name;
        Location = location;
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

  1. Defining the Dictionary:

    • A dictionary named universities maps country names (string) to a list of University objects.
  2. Enumerating Keys:

    • The Keys property is used to list all available countries. This makes it easy for the user to select a country.
  3. User Input Validation:

    • The ContainsKey method ensures that the program doesn’t crash when an invalid country is entered.
  4. Displaying Results:

    • For the selected country, the top universities (up to 5) are displayed using the Take method from LINQ.

Sample Output

Input Scenario 1: Valid Country

Available countries:
USA
UK

Enter a country:
USA

Top universities in USA:
- MIT, located in Massachusetts
- Stanford University, located in California
- Harvard University, located in Massachusetts
Enter fullscreen mode Exit fullscreen mode

Input Scenario 2: Invalid Country

Available countries:
USA
UK

Enter a country:
Canada
Country not found.
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Dictionary Keys Enumeration: Use the Keys property to access all keys in a dictionary.
  • Key Validation: Always validate user input with ContainsKey.
  • LINQ for Filtering: Methods like Take make it easy to limit and process collections.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more