【发布时间】:2020-10-15 13:52:09
【问题描述】:
这是我创建字典的函数:
public int Scale(string value)
{
//some calculs
int result = 19; // or int between 0 and 40
this.stringToInt = new Dictionary<string, int>()
{
{"1p",00},{"2p",01},{"3p",03} ... {"300p",40}
};
// Here I try to do something like that: if(result == (int in dictionary) return associate string
}
我尝试了以下代码:
if (this.stringToInt.ContainsValue(result)
{
return this.stringToInt[result]; // I don't know what to write between hook (result doesn't work).
}
我不知道如何返回关联字符串。
提前感谢您的帮助!
【问题讨论】:
-
您必须在字典
new Dictionary<int, string>中交换您的 int 和字符串,然后使用.ContainsKey() -
如果@nanu_nana 建议不起作用(如果 int 值不唯一),您可以使用简单的 linq:return stringToInt.First(x=> x.Value == result).Key。但是,如果它们不是唯一的,您将获得第一个匹配的字符串键。理想情况下,如果适用,使用 ContainsKey 是最佳解决方案。
-
最终,这是使用字典向后。如果您需要偶尔为适度大小的集合执行此操作,那很好 - 但如果您需要经常执行此操作,或者对于非常大的数据:您应该考虑拥有两个字典 - 每个方向一个
-
@nanu_nana 或
TryGetValue -
您的搜索似乎没有“the”方向。在this question 中,您正在按键搜索值,而在这里您正在按值搜索键。因此,您可能需要一些新的数据结构,其中的键是您的键和值的组合,并根据两者计算哈希。
标签: c# dictionary compare