2013-12-23 26 views
0

我正在使用c#創建一個簡單字典。這裏是重要的代碼:字典應用程序未能返回結果

enOutput.Text = "Ní Rézelnasin/No Results"; 
      string dictText = DictResource.knendict.ToString(); 

      string[] lines = dictText.Split('\n'); 
      foreach (string line in lines) 
      { 
       string[] entries = line.Split('='); 

       if (knInput.Text == entries[1]) 
       { 

        enOutput.Text = entries[0]; 
       } 
      } 

但是,它似乎沒有工作。字典格式的結構是這樣的:

english word=knashta equivalent 

一樣,

hello=ahoj 
the=sé 
dictionary=diktsíonarísinsta 

但是,如果我進入ahoj,我沒有得到任何結果回來。

我在做什麼錯?

編輯,後嘗試:

var text = DictResource.knendict.ToString(); 
var dict = text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries) 
      .Select(part => part.Split('=')) 
      .ToDictionary(split => split[1], split => split[0]); 
enOutput.Text = dict[knInput.Text]; 

我收到此錯誤信息:

See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box. 

************** Exception Text ************** 
System.ArgumentException: An item with the same key has already been added. 
    at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) 
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) 
    at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) 
    at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector) 
    at ShellApp.Dictionary.getEnglish_Click(Object sender, EventArgs e) 
    at System.Windows.Forms.Control.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
    at System.Windows.Forms.Control.WndProc(Message& m) 
    at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
    at System.Windows.Forms.Button.WndProc(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
+2

你是如何將這兩對添加到字典?你有沒有把鑰匙/價值看成是錯誤的方式? – James

回答

2

看來愚蠢是建立一個字典式的應用程序,而不是使用Dictionary<key, value>型結構...

var text = DictResource.knendict.ToString(); 
var dict = text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries) 
      .Select(part => part.Split('=')) 
      .ToDictionary(split => split[1], split => split[0]); 

此代碼將建立一個knashta equivalent -> english translation的字典,讓你和我它使用它像

Console.WriteLine(dict["ahoj"]); // hello 
+0

這似乎更容易/更好。我會試試看。 – Igor

+0

現在我收到一條錯誤消息。 – Igor

+1

@Igor請記住,這不是一個幫助臺網站。你不應該改變你的問題來解決不同的問題,並期望有人在你嘗試完成你的代碼的過程中不斷改正他們的答案。 – BartoszKP