[英]Retrieving the key of a value from a hash table c#
我有一个哈希表,其中包含一个^ j的值。 j是键,^ j是值。 我现在正在计算另一个值a ^ m。 我基本上想看看^ m是否在哈希表中。 我使用了ContainsValue fn。 找到价值。 我如何找到价值的关键?
这里是我想要实现搜索值的一小部分。
Dictionary<BigInteger, BigInteger> b = new Dictionary<BigInteger, BigInteger>();
***add a bunch of BigIntegers into b***
for(int j=0; j < n; j++)
{
z = q* BigInteger.ModPow(temp,j,mod);
***I want to implement to search for z in b here****
}
这会改变什么吗? 我在for循环中搜索的事实?
最快的方法可能是遍历哈希表的DictionaryEntry
项以查找值,从而为您提供密钥。 我不知道怎么做。
首先,你绝对应该使用Dictionary<TKey, TValue>
而不是Hashtable
- 如果你使用.NET 4中的BigInteger
,没有理由不在任何地方使用泛型集合。 大多数情况下,您可能会发现它的使用方式没有区别 - 只需创建它:
Dictionary<BigInteger, BigInteger> map =
new Dictionary<BigInteger, BigInteger>();
首先。 有一点需要注意的是,如果该键不存在于地图索引会抛出异常-使用TryGetValue
如果它存在和获取价值bool
说这是否确实存在。
至于按值查找密钥 - 没有办法从Dictionary
中有效地完成。 您可以搜索所有条目,这是使用LINQ最容易完成的:
var key = map.Where(pair => pair.Value == value)
.Select(pair => pair.Key)
.First();
但是这会迭代整个字典直到找到匹配,所以这是一个O(n)操作。
如果你想有效地做到这一点,你应该保留两个字典 - 一个从a
到a^j
,一个从a^j
到a
。 添加条目时,可以双向添加。 Stack Overflow上的某个地方我有一些类的示例代码可以为你做这个,但我怀疑我能够轻松找到它。 编辑:有一个与多个映射科佩斯这里 ; “单一映射”版本在该答案之下。
无论如何,一旦你有两个字典,每个方向一个,这很容易 - 显然你只是在第二个字典中查找a^m
作为键来找到创建它的原始值。
请注意,您需要考虑两个原始键是否有可能以相同的值结束 - 此时您显然无法在一个反向字典中同时使用这两个映射(除非它是一个Dictionary<BigInteger, List<BigInteger>>
或类似的东西)。
private object GetKeyByValue(object searchValue)
{
foreach (DictionaryEntry entry in myHashTable)
{
if (entry.Value.Equals(searchValue))
{
return entry.Key;
}
}
return null;
}
编辑: 更改为使用Dictionary<TKey, TValue>
Dictionary<TKey, TValue>
是IEnumerable<KeyValuePair<TKey, TValue>>
。 如果您直接对其进行foreach
,则可以获得每个条目的键和值。
class SomeType
{
public int SomeData = 5;
public override string ToString()
{
return SomeData.ToString();
}
}
// ...
var blah = new Dictionary<string, SomeType>();
blah.Add("test", new SomeType() { SomeData = 6 });
foreach (KeyValuePair<string, SomeType> item in blah)
{
if(e.Value.SomeData == 6)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
}
如果您有更新版本的.Net框架,可以使用Linq查找匹配项,并将它们放在自己的集合中。 这是一个显示Linq语法的代码示例:
using System;
using System.Collections;
using System.Linq;
class SomeType
{
public int SomeData = 5;
public override string ToString()
{
return SomeData.ToString();
}
}
class Program
{
static void Main(string[] args)
{
var blah = new Dictionary<string, SomeType>();
blah.Add("test", new SomeType() { SomeData = 6 });
// Build an enumeration of just matches:
var entriesThatMatchValue = blah
.Where(e => e.Value.SomeData == 6);
foreach (KeyValuePair<string, SomeType> item in entriesThatMatchValue)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
// or: ...
// Build a sub-enumeration of just keys from matches:
var keysThatMatchValue = entriesThatMatchValue.Select(e => e.Key);
// Build a list of keys from matches in-line, using method chaining:
List<string> matchingKeys = blah
.Where(e => e.Value.SomeData == 6)
.Select(e => e.Key)
.ToList();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.