我正在使用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)
你是如何將這兩對添加到字典?你有沒有把鑰匙/價值看成是錯誤的方式? – James