我该如何使用listDictionary? [英] How can i use listDictionary?
问题描述
我可以填补我listdictinary但是,如果在运行错误返回给我的foreach(在ld.Keys字符串KY)(无效操作异常是未处理)
错误详细信息:创建一个指向样本收集的名单之后已经改变。 C#
ListDictionary LD =新ListDictionary();
的foreach(DataColumn的DC IN dTable.Columns)
{
的MessageBox.show(dTable.Rows [0] [DC]的ToString());
ld.Add(dc.ColumnName,dTable.Rows [0] [DC]的ToString());
}
的foreach(在ld.Keys串KY)
如果(int.TryParse(LD [奇]的ToString(),出QuantityInt))
LD [奇] =整数;
否则,如果(double.TryParse(LD [奇]的ToString(),出QuantityDouble))
LD [奇] =双规;
其他
LD [奇] =nvarchar的;
你的第二个foreach循环设置LD [奇] =什么改变ListDictionary;你不能用一个foreach循环做到这一点,因为在内部它使用一个枚举。虽然使用枚举是非法的改变集合被枚举。
相反,使用for循环。
更妙的是,做这件事在dTable.Columns一个循环,将该值设置在词典中,当您添加的每一项。
ListDictionary LD =新ListDictionary();
的foreach(DataColumn的DC IN dTable.Columns)
{
的MessageBox.show(dTable.Rows [0] [DC]的ToString());
字符串值;
如果(int.TryParse(dTable.Rows [0] [DC]的ToString(),出QuantityInt))
值=整数;
否则,如果(double.TryParse(dTable.Rows [0] [DC]的ToString(),出QuantityDouble))
值=双规;
其他
值=nvarchar的;
ld.Add(dc.ColumnName,价值);
}
i can fill my listdictinary but, if running error returns to me in " foreach (string ky in ld.Keys)"(invalid operation Exception was unhandled)
Error Detail : After creating a pointer to the list of sample collection has been changed. C#
ListDictionary ld = new ListDictionary();
foreach (DataColumn dc in dTable.Columns)
{
MessageBox.Show(dTable.Rows[0][dc].ToString());
ld.Add(dc.ColumnName, dTable.Rows[0][dc].ToString());
}
foreach (string ky in ld.Keys)
if (int.TryParse(ld[ky].ToString(), out QuantityInt))
ld[ky] = "integer";
else if(double.TryParse(ld[ky].ToString(), out QuantityDouble))
ld[ky]="double";
else
ld[ky]="nvarchar";
Your second foreach loop alters the ListDictionary by setting ld[ky] = "whatever"; You can't do this with a foreach loop, because internally it uses an enumerator. While using an enumerator it is illegal to alter the collection being enumerated.
Instead, use a for loop.
Even better, do the whole thing in a single loop on dTable.Columns, setting the value in the dictionary when you are adding each item.
ListDictionary ld = new ListDictionary();
foreach (DataColumn dc in dTable.Columns)
{
MessageBox.Show(dTable.Rows[0][dc].ToString());
string value;
if (int.TryParse(dTable.Rows[0][dc].ToString(), out QuantityInt))
value = "integer";
else if(double.TryParse(dTable.Rows[0][dc].ToString(), out QuantityDouble))
value="double";
else
value="nvarchar";
ld.Add(dc.ColumnName, value);
}
这篇关于我该如何使用listDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!