C# 使用linq到xml更新xml文件
我正在尝试使用GUI中的以下代码更新xml文件C# 使用linq到xml更新xml文件,c#,linq-to-xml,C#,Linq To Xml,我正在尝试使用GUI中的以下代码更新xml文件 var Settings = (from e in config.Descendants("Settings") from kvpair in e.Elements("add") select new { Name = kvpair.Attribute("key").Value,
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个条目需要更新,我正以这种方式尝试,以避免每个udpate的if语句
Settings["CustomerA"].Node.Attribute.value=settings.containskey("CustomerA") ?txtCustomerA.Text:null;
但是上面的代码抛出异常,因为字典中不存在密钥
我只是想找到一个解决办法,以避免使用20条if语句。如果有人能指导我,我会很高兴。您可以构建一个映射字典并循环使用它:
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;
}
var映射=新字典
{
{“CustomerA”,()=>txtCustomerA.Text},
{“CustomerB”,()=>txtCustomerB.Text},
{“CustomerC”,()=>txtCustomerC.Text},
//等等。。。。
};
foreach(映射中的var对)
{
Settings[pair.Key]=(Settings.ContainsKey(pair.Key))?pair.Value():null;
}
它仍然不能让你节省大量的编码,但它确实避免了20+
if
语句。我假设所有的不规则情况都是复制过程中的打字错误?