我有一个项目,我必须创建自己的线性散列、桶散列和二次散列算法,所以我选择散列一些字符串,但我遇到了一个小问题,我有 2 个 ListBox:
- 一个充满字符串的 ListBox
- 一个列表框,里面装满了这些字符串的哈希值
我可以毫无问题地打印字符串,但是当我单击一个按钮时,我不知道如何将它们相应的哈希打印到另一个 ListBox 中。
这是我的代码:
表格.cs
private void btnLinearHash_Click(object sender, EventArgs e)
{
// Initialize Hash.cs (see below for code)
Hash.LinearHash linearHash = new Hash.LinearHash();
RandomArrayGen randGen = new RandomArrayGen();
// Clear both ListBoxes
lbHashStrings.Items.Clear();
lbHashesOfStrings.Items.Clear();
for (int i = 0; i < 12; i++)
{
// Generate 12 random upper and lowercase strings using RandomArrayGen.cs (see https://pastebin.com/jRsG5r1E)
lbHashStrings.Items.Add(randGen.GenRandomStrings(12, true, true));
}
for (int i = 0; i < lbHashStrings.Items.Count; i++)
{
// Generate a hash of a string and store it into a Dictionary (see Hash.cs)
linearHash.GenerateHashOfString(lbHashStrings.Items[i].ToString());
lbHashesOfStrings.Items.Add(linearHash.FindHashCodeInDictionary(lbHashStrings.Items[i].ToString()));
}
}
哈希.cs
public class LinearHash
{
private Dictionary<byte[], string> linearHashArray = new Dictionary<byte[], string>();
private byte[] hashCode;
public void GenerateHashOfString(string stringToHash)
{
hashCode = Encoding.ASCII.GetBytes(stringToHash);
linearHashArray.Add(hashCode, stringToHash);
}
public string FindHashCodeInDictionary(string StringToFind)
{
byte[] HashOfStringToFind = Encoding.ASCII.GetBytes(StringToFind);
//For some reason, this keeps returning false
foreach (var keyPairValue in linearHashArray)
{
if ((linearHashArray.ContainsKey(HashOfStringToFind) && linearHashArray.ContainsValue(StringToFind))
{
return Encoding.UTF8.GetString(HashOfStringToFind);
}
}
return "Hash not found";
}
}
所以,我的问题是:我做错了什么?为什么 Hash.cs 中的 foreach 返回 false?