我正在开发一个拼字游戏骗子类的程序,用户输入一组字母,在字母有点混乱之后,将它们与我存储在数据库中的单词列表进行比较。因为在数据库中搜索每个字母组合非常慢,所以我尝试先将单词存储在 List 中,这样它们就可以在内存中使用,这确实提高了性能。但是我想通过将单词列表存储在哈希表中的 List 中来加快速度,其中键是单词的第一个字母,但我有点不知道如何去做。
我所拥有的(显然不会工作)是:
public Hashtable populateWordTable()
{
Hashtable wordTable = new Hashtable();
List<string> wordTableWordList = new List<string>();
connect = new SqlConnection(connectionString);
SqlCommand find = new SqlCommand("Select * FROM English order by Word", connect);
// starting with first record, store each word into the List<string> wordlist
SqlDataReader dr = null;
int found = 0;
try
{
connect.Open();
dr = find.ExecuteReader();
string key = string.Empty;
string keyStartingPosition = "a";
while (dr.Read())
{
// if word is present
if (!dr.IsDBNull(0))
{
found = Convert.ToInt32(dr[0]);
key = dr[1].ToString().Substring(0, 1);
}
if (found > 0)
{
// if we have transitioned to the next letter in the alphabet
if (key != keyStartingPosition)
{
wordTable.Add(keyStartingPosition, wordTableWordList);
List<string> newList = new List<string>();
newList.Add(dr[1].ToString());
keyStartingPosition = key;
}
// still in the same letter in the alphabet
else
{
wordTableWordList.Add(dr[1].ToString());
}
}
}
}
catch (Exception ex)
{
}
finally
{
connect.Close();
}
return wordTable;
}