我正在从数据表中获取值并放入 Dictionary<string,string>
:
Dictionary<string, string> mydic= new Dictionary<string, string>();
我的 ex 数据表是
Value RowOrder
page1 01
page2 00
page3 00
我正在使用 LINQ 获取 RowOrder
根据给定的值放入mydic
:
string id = (from DataRow dr in table3.Rows where (string)dr["Value"] == formula
select (string)dr["RowOrder"]).FirstOrDefault();
mydic.Add(id,Value);
如果我运行它,会显示错误:
"An item with the same key has already been added."
如何克服这个问题。我要page1
, page2
, page3
应添加值 01
, 00
, 00
分别
最佳答案
在添加之前需要检查字典是否已经有键:
if(!mydic.ContainsKey(id))
{
mydic.Add(id, Value);
}
字典不能包含具有相同键的两个项目,如果您期望重复的 id 值,您需要考虑使用不同的数据结构。
也许是 List<Tuple<string, string>>
?
关于c#如果键存在于字典中仍然添加字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20949060/