如何在C#中按值获取字典键?
Dictionary types = new Dictionary()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
我想要这样的东西:
getByValueKey(string value);
getByValueKey("one")必须返回"1" 。
最好的方法是什么? 也许HashTable,SortedLists?
#1楼
您可以这样做:
通过遍历字典中的所有KeyValuePair (如果字典中有很多条目,这将对性能产生很大的影响)
使用两个字典,一个用于值到键的映射,另一个用于键到值的映射(这将占用内存的两倍)。
如果不考虑性能,则使用方法1;如果不考虑内存,则使用方法2。
同样,所有键都必须是唯一的,但是值不必是唯一的。 您可能有多个具有指定值的键。
有什么原因不能扭转键值关系?
#2楼
值不一定必须是唯一的,因此您必须进行查找。 您可以执行以下操作:
var myKey = types.FirstOrDefault(x => x.Value == "one").Key;
如果值是唯一的,并且插入频率比读取的频率低,请创建一个反向字典,其中值是键,而键是值。
#3楼
我有很简单的方法来做到这一点。 对我来说很完美。
Dictionary types = new Dictionary();
types.Add("1", "one");
types.Add("2", "two");
types.Add("3", "three");
Console.WriteLine("Please type a key to show its value: ");
string rLine = Console.ReadLine();
if(types.ContainsKey(rLine))
{
string value_For_Key = types[rLine];
Console.WriteLine("Value for " + rLine + " is" + value_For_Key);
}
#4楼
types.Values.ToList().IndexOf("one");
Values.ToList()将您的字典值转换为对象列表。 IndexOf(“ one”)搜索新列表以查找“ one”,并返回与字典中键/值对的索引匹配的Index。
此方法不关心字典键,它仅返回您要查找的值的索引。
请记住,词典中可能有多个“一个”值。 这就是没有“获取密钥”方法的原因。
#5楼
以下代码仅在包含唯一值数据时才有效
public string getKey(string Value)
{
if (dictionary.ContainsValue(Value))
{
var ListValueData=new List();
var ListKeyData = new List();
var Values = dictionary.Values;
var Keys = dictionary.Keys;
foreach (var item in Values)
{
ListValueData.Add(item);
}
var ValueIndex = ListValueData.IndexOf(Value);
foreach (var item in Keys)
{
ListKeyData.Add(item);
}
return ListKeyData[ValueIndex];
}
return string.Empty;
}