我目前正在努力学习字典是如何工作的,但我找不到怎么做标题上说的。
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");
}
}
}
}现在,代码正在检查字典值部分中的字符串“Pancake”是否存在。我想要的是,要检查字典的第一个键(在当前情况下是“Fiora”),是否有字符串“Pancake”。
发布于 2022-09-11 13:17:39
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;
}
}嗨,希望这能解决你的问题!
发布于 2022-09-13 00:02:58
您可能需要考虑ToLookup,然后可以这样做:
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"]));
}输出Fiora, Darius。
https://stackoverflow.com/questions/73678828
复制相似问题