2012-02-15 103 views
0

我想从我的GUI中使用下面的代码来更新xml文件。使用LINQ更新xml文件到xml

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; 

上面的代码工作正常:

当我想检查开关是否存在于字典或不 我使用

if(settings.containskey("CustomerA")) 
    Settings["CustomerA"].Node.Attribute.value=txtCustomerA.Text; 

这工作得很好了。

但我有说,20项被更新我试图以这种方式序,以避免if语句每个UDPATE

Settings["CustomerA"].Node.Attribute.value=settings.containskey("CustomerA") ?txtCustomerA.Text:null; 

,但上面的代码抛出异常,该键不存在于字典? ??

我只是好奇的工作,以避免20如果statement.I会很高兴,如果有人可以指导我。

+0

我假设所有的情况下,违规行为是重现你的问题错别字? – Aren 2012-02-15 16:22:18

+0

@Aren:是的,有错别字 – Macnique 2012-02-15 16:29:15

回答

1

你可以建立一个映射字典和循环遍历它:

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; 
} 

这还真是不会让你节省大量的编码,但它确实避免20+ if语句。