2014-11-22 29 views
0

我正在開發一本詞典,並且有大約110,000個單詞。在windows_load中,我加載了一個已排序字典中的所有單詞。然後,當用戶開始在文本框中輸入字符時,我的程序應搜索已排序的字典並顯示以列表框中的這些字符開頭的單詞。按文本框中鍵入的字符過濾單詞集合,並在列表框中顯示結果單詞

例如,當用戶在文本框中輸入「COM」我想要的程序,以顯示所有單詞開始在列表框中

我想知道如果我使用的是正確的數據結構「COM」,但它搜索根據存儲在其中的密鑰。

namespace StringDictionaryClass 
{ 
public partial class MainWindow : Window 
{ 
    SortedDictionary<string, string> sortedDic = new SortedDictionary<string, string>(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     LoadWords(); 
    } 
    private void LoadWords() 
    { 
     int counter = 0; 
     string word; 
     // Read the file and display it word by word. 
     string path = AppDomain.CurrentDomain.BaseDirectory; 
     if (File.Exists(path + "\\Words.txt")) 
     { 
      System.IO.StreamReader file = new System.IO.StreamReader(path + "\\Words.txt"); 
      while ((word = file.ReadLine()) != null) 
      { 
       sortedDic.Add(word, ""); 
       counter++; 
      } 
      file.Close(); 
     } 
    } 

    private void earchBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     string key = searchBox.Text; 
     foreach (KeyValuePair<string, string> dictionaryEntry in sortedDic) 
     { 
      if (key == dictionaryEntry.Key) 
      { 
       listBoxWords1.Items.Add(dictionaryEntry.Key); 
      } 

     } 
    } 
} 
} 
+0

你能告訴我究竟發生了什麼嗎? – 2014-11-22 06:04:40

回答

1

的問題是,你檢查,如果整個搜索字符串在字典中,您實際上只希望找到與搜索文本開頭的單詞的密鑰相匹配。

您可以在您的searchBox_TextChanged處理程序中執行以下操作。

// Get the words in the dictionary starting with the textbox text. 
var matching = sortedDic.Keys.Where(x => x.StartsWith(searchText.Text)).ToList(); 


// Assign the values to the listbox. 
listboxWords1.Items.AddRange(matching); 
+0

這個和平代碼的問題是,通過輸入或刪除每個字符將數百個單詞添加到列表框中。它工作非常慢並且消耗大量內存和CPU。請改善嗎? – Hadi 2014-11-22 09:43:15

+0

那麼你有這個運行的每一次文本在文本框中更改。也許在用戶在文本框中暫停時在單獨的線程或定時器中運行這個選項是您想要的。 – jhenninger 2014-11-22 15:34:57

+0

是的。問題是,如果我輸入'A',它會找到所有以'A'開始的單詞,並將它們全部插入到var匹配中。然後,當我輸入'p'時,它也會插入以'ap'開頭的所有單詞等等。然後所有人都添加到列表框中。 – Hadi 2014-11-23 10:43:06

相關問題