按值获取字典键 [英] Get dictionary key by value

查看:40
本文介绍了按值获取字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中按值获取字典键?

How do I get a Dictionary key by value in C#?

Dictionary<string, string> types = new Dictionary<string, string>()
{
    {"1", "one"},
    {"2", "two"},
    {"3", "three"}
};

我想要这样的东西:

getByValueKey(string value);

getByValueKey(one") 必须返回 1".

最好的方法是什么?也许是 HashTable 或 SortedLists?

What is the best way do this? Maybe HashTable or SortedLists?

推荐答案

值不一定必须是唯一的,因此您必须进行查找.你可以这样做:

Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

如果值是唯一的并且插入频率低于读取频率,则创建一个逆字典,其中值是键,键是值.

If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

这篇关于按值获取字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆