Skip to main content
 首页 » 编程设计

c#之使用 foreach 添加到 Dictionarystring, string>

2024年02月23日16artech

确保 optionValue 在以下场景中始终唯一的最佳方法是什么?

public Dictionary<string, string> Dict = new Dictionary<string, string>(); 
 
    foreach (string optionKey in i.options.Keys) 
    { 
       string optionValue = i.options.Values.ToString(); 
       Dict.Add(optionKey, optionValue); 
    } 

编辑:i.options 包含一个键和一个值对。我需要确保为每个键将相应的值添加到字典中

EDIT2:修正了 Dict.Add(optionKey, optionValue) 的顺序

请您参考如下方法:

只是测试一下:

if(!Dict.ContainsKey(optionValue)) 
   Dict.Add(optionValue, optionKey) 

根据你的变量名,看起来你的键和值被颠倒了,如果 optionKey 是你的查找键,它应该是:

Dict.Add(optionKey, optionValue);