How do I check what is the value against the specific key?

Viewed 36

I am currently trying to learn how Dictionaries work, and I can't find how to do what the title says.

using System;
using System.Collections.Generic;

namespace Demo.Aiman1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> guestsFoods = new Dictionary<string, string>();
            guestsFoods.Add("Fiora", "Pancakes");
            guestsFoods.Add("Darius", "Pancakes");
            guestsFoods.Add("Mordekaiser", "Apple");
            if (guestsFoods.ContainsValue("Pancakes"))
            {
                Console.WriteLine("Something");
            }
        }
    }
}

Right now, the code is checking if the string "Pancakes" exists anywhere in the Value part of the dictionary. What I want is, to check if against the 1st Key of the dictionary("Fiora" in the current case), there is the string "Pancakes".

2 Answers
        Dictionary<string, string> guestsFoods = new Dictionary<string, string>();
        guestsFoods.Add("Fiora", "Pancakes");
        guestsFoods.Add("Darius", "Pancakes");
        guestsFoods.Add("Mordekaiser", "Apple");
        foreach (var kvp in guestsFoods)
        {
            if (kvp.Value== "Pancakes")
            {
                Console.WriteLine($"{kvp.Key}");
                break;
            }
        }

Hi, hopefully this solves your problem!

You might want to consider ToLookup, then you can do this:

var guestsFoods = new Dictionary<string, string>()
{
    { "Fiora", "Pancakes"},
    { "Darius", "Pancakes"},
    { "Mordekaiser", "Apple"},
};

var opposite = guestsFoods.ToLookup(x => x.Value, x => x.Key);

if (opposite.Contains("Pancakes"))
{
    Console.WriteLine(String.Join(", ", opposite["Pancakes"]));
}

That outputs Fiora, Darius.

Related