c#如果键存在于字典中仍然添加字典中的值

标签 c# linq dictionary

我正在从数据表中获取值并放入 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/

相关文章:

c# - 将逗号分隔的字符串转换为 int 列表并验证

c# - DataTable AsEnumerable 匹配单个值

python - 从 pandas 数据透视表生成 Plotly 热图

python - 这两个 python for 循环是一回事吗?

c# - 将int放入各种对象数组时得到 'NullReferenceException'

c# - 在 C# 中计划任务并继续

c# - lambda 表达式中的子句

Python csv(两列: key/value) to Dictionary

c# - .NET 项目的 SQLite 或 SQL Server Compact

C# 获取标签并更改文本