【发布时间】:2013-12-23 00:58:14
【问题描述】:
我正在使用 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)
【问题讨论】:
-
您如何将这些对添加到字典中?您是否可能以错误的方式使用键/值?