如何在字典中更改KeyPairValue的值?

时间:2015-06-28 12:29:01

标签: c# dictionary key-value

我在xml中使用KeyValuePair,如下所示:

<list_pair key="WorkMode">
    <str_pair key="1" value="&amp;1 Ready" />
    <str_pair key="2" value="&amp;2 Not ready" />
</list_pair>

我可以将它们添加到字典中:

foreach (XmlNode wmNode in wmNodeList)
    wmDictionary.Add(wmNode.Attributes["key"].Value, wmNode.Attributes["value"].Value);

由于我希望在应用程序界面的菜单中很好地显示该值,因此我想更改要显示的值。例如,我想更改值&#34;&amp; 1准备&#34;到&#34; 1准备好&#34;。那么,我该怎么做呢?这是我到目前为止所做的:

foreach(var key in wmDictionary.Keys)
{
    switch (key)
    {
        //How to do the changes?
    }
}

请帮忙。

7 个答案:

答案 0 :(得分:2)

如果它只是您要删除的&符号,则可以将其作为LINQ查询的一部分。

foreach (XmlNode wmNode in wmNodeList)
    wmDictionary.Add(wmNode.Attributes["key"].Value, 
                     wmNode.Attributes["value"].Value.ToString().Replace("&", "").Trim());

答案 1 :(得分:1)

为什么不在填充字典时简单地使用string.Replacestring.TrimStart

wmNode.Attributes["value"].Value.Replace("&amp;", "");

答案 2 :(得分:1)

首先,当您希望修改值时,不应该打开键。此外,您根本不应该进行切换:更好的方法是设置带翻译的地图,并使用它来查找翻译的值,如下所示:

// This dictionary can be defined on the class
// as a private static readonly member.
var translations = new Dictionary<string,string> {
    {"original1", ""translation1}
,   {"original2", "translation2"}
};
foreach(var kvp in wmDictionary) {
    string translated;
    if(!translations.TryGetValue(kvp.Value, out translated)){
        translated=kvp.Value;
    }
    Console.WriteLine("Key={0} Translated value={1}", kvp.Key, translated);
}

答案 3 :(得分:1)

var dic = new Dictionary<string, string>();    
dic.Keys.ToList().ForEach(dd => dic[dd] = dic[dd].Replace("&amp;", ""));

答案 4 :(得分:0)

为什么需要切换?喜欢以下 -

foreach(var key in wmDictionary.Keys)
{
    wmDictionary[key] = "do whatever operation you want to do";
}

答案 5 :(得分:0)

所以我明白你要删除你的“&amp;”从菜单选项,这里是您可以使用的代码示例,我只需将其键入记事本并将其粘贴到此处以给您一个想法,

    foreach(var key in wmDictionary.Keys)
 {
   switch (key)
   {
     string originalVal = wmDictionary[key].Value;
     string newVal = originalVal.replace("&","");
     wmDictionary[key] = newVal
   }
 }

答案 6 :(得分:0)

请勿修改foreach阅读thisthis

中的馆藏

做这样的事情:

private string ModifyKey(string key){
    return key.Replace("&amp;","");
}

在将其添加到字典

之前修改它
foreach (XmlNode wmNode in wmNodeList){
    wmDictionary.Add(ModifyKey(wmNode.Attributes["key"].Value), wmNode.Attributes["value"].Value);
}