Reputation: 1034
I am trying to update an xml file using the following code from my GUI.
var Settings = (from e in config.Descendants("Settings")
from kvpair in e.Elements("add")
select new
{
Name = kvpair.Attribute("key").Value,
Node = kvpair
}).ToDictionary(x => x.Name, y => y);
Settings["CustomerA"].Node.Attribute.value=txtCustomerA.Text;
The above code works fine:
When i wanted to check whether the key is present in dictionary or not i am using
if(settings.containskey("CustomerA"))
Settings["CustomerA"].Node.Attribute.value=txtCustomerA.Text;
This works fine too.
But i have say 20 entries to be updated i am trying in this fashion inorder to avoid if statement for each udpate
Settings["CustomerA"].Node.Attribute.value=settings.containskey("CustomerA") ?txtCustomerA.Text:null;
but the above code throws exception the key doesn't exists in the dictionary ???
I was just curious for a work around in order to avoid 20 if statements.I will be glad if some one can guide me.
Upvotes: 0
Views: 207
Reputation: 55966
You can build a mapping dictionary and loop through it:
var mappings = new Dictionary<string, Func<string>>
{
{"CustomerA", () => txtCustomerA.Text},
{"CustomerB", () => txtCustomerB.Text},
{"CustomerC", () => txtCustomerC.Text},
// etc....
};
foreach(var pair in mappings)
{
Settings[pair.Key] = (Settings.ContainsKey(pair.Key)) ? pair.Value() : null;
}
It still really doesn't let you save a lot of coding but it does avoid 20+ if
statements.
Upvotes: 1