Reputation: 579
I've KeyValuePair in xml like this:
<list_pair key="WorkMode">
<str_pair key="1" value="&1 Ready" />
<str_pair key="2" value="&2 Not ready" />
</list_pair>
I'm able to add them into a dictionary:
foreach (XmlNode wmNode in wmNodeList)
wmDictionary.Add(wmNode.Attributes["key"].Value, wmNode.Attributes["value"].Value);
Since I want the value to be displayed nicely in a menu in my application interface, I want to change the value to be displayed. For example, I want to change the value "& 1 Ready" to "1 Ready". So, how can I do that changes? Here's what I've done so far:
foreach(var key in wmDictionary.Keys)
{
switch (key)
{
//How to do the changes?
}
}
Please help.
Upvotes: 2
Views: 369
Reputation: 727067
First, you shouldn't be switching on key when you wish tomodify value. Moreover, you shouldn't be switching at all: a better way is to set up a map with translations, and use it to look up translated values, like this:
// 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);
}
Upvotes: 1
Reputation: 2754
var dic = new Dictionary<string, string>();
dic.Keys.ToList().ForEach(dd => dic[dd] = dic[dd].Replace("&", ""));
Upvotes: 1
Reputation: 82534
Why not simply use string.Replace
or string.TrimStart
when populating the dictionary?
wmNode.Attributes["value"].Value.Replace("&", "");
Upvotes: 1
Reputation: 3013
Don't modify collections in foreach
read this and this
Do something like this:
private string ModifyKey(string key){
return key.Replace("&","");
}
And modify it before adding it to the dictionary
foreach (XmlNode wmNode in wmNodeList){
wmDictionary.Add(ModifyKey(wmNode.Attributes["key"].Value), wmNode.Attributes["value"].Value);
}
Upvotes: 0
Reputation: 3384
So what i understood was you want to remove your "&" from menu options, here is the code example you can use, i just typed it into notepad and paste it over here to give you an idea,
foreach(var key in wmDictionary.Keys)
{
switch (key)
{
string originalVal = wmDictionary[key].Value;
string newVal = originalVal.replace("&","");
wmDictionary[key] = newVal
}
}
Upvotes: 0
Reputation: 47
Why would you need switch? Do like following -
foreach(var key in wmDictionary.Keys)
{
wmDictionary[key] = "do whatever operation you want to do";
}
Upvotes: 0
Reputation: 69372
If it's just the ampersands you want to remove, you can put it as part of your LINQ query.
foreach (XmlNode wmNode in wmNodeList)
wmDictionary.Add(wmNode.Attributes["key"].Value,
wmNode.Attributes["value"].Value.ToString().Replace("&", "").Trim());
Upvotes: 2