我正在使用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)
答案 0 :(得分: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